Spring入門(三) 註解配置

2021-09-27 08:59:38 字數 1061 閱讀 8044

除了使用xml檔案配置外,從spring 3.0開始還提供了使用註解進行配置。

使用註解進行配置,可以簡化繁瑣的xml配置,將上例的helloworld修改為註解配置。

首先我們看xml檔案的改動:

<?xml version="1.0" encoding="utf-8"?>

xmlns

=""xmlns:xsi

=""xmlns:context

=""xsi:schemalocation

="/spring-beans.xsd

/spring-context.xsd"

>

<

context:component-scan

base-package

="com.example.assembly"

>

context:component-scan

>

beans

>

可以看到,現在的xml檔案已經沒有手動配置的bean了,除了spring的配置檔案頭部,只有乙個context:component-scan標籤,該標籤表示ioc容器自動檢測包下的類,並為新增了對應注釋的bean進行註冊。

類檔案變為:

package com.example.assembly;

import org.springframework.stereotype.component;

@component

("hello"

)public

class

assemblytest

public

void

setname

(string name)

public

void

say(

)}

僅僅是在類上新增了乙個註解@component,相當於告訴ioc容器掃瞄到時需要為這個類註冊bean。

執行結果和之前相同。

這樣就大大簡化了bean的配置,常用的註解還有很多,在此僅以乙個簡單的例子拋磚引玉。

spring 註解配置

以前我們在配置spring檔案的時候一般都是這麼寫 autowire有4種自動裝配的型別 byname 把與bean的屬性具有相同名字 或者id 的其他bean自動配置到bean對應的屬性中。bytype 把與bean的屬性具有相同型別的其他bean自動配置到bean對應的屬性中。construct...

spring註解配置

匯入依賴 beans 建立person類 public class person public void setusername string username public string getpassword public void setpassword string password 建立p...

Spring註解配置

componentscan的value屬性和basepackages屬性等價。bean註解用於將當前方法的返回值作為bean物件放入spring容器中,預設id為方法名稱,也可以使用name屬性指定。如果方法有引數,也會在spring容器中查詢。propertysource使用properties檔...