經過對XML版本進行修改:http://www.cnblogs.com/likailan/p/3446821.htmlhtml
spring-framework-2.5.6 版須要導入如下包:
和XML版同樣。spring
spring-framework-3.2.4 版須要導入如下包:
和XML版同樣。測試
其餘版本沒有做測試。this
經過 Annotation 聲明 bean 則不須要在配置文件中聲明瞭,把配置文件修改成:spa
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.spring" /> </beans>
1.添加context明名空間(代碼四、七、8行)。code
2.添加代碼 <context:component-scan base-package="com.spring" /> 告訴Spring掃描 com.spring 包(包括子包)下的全部類而找到bean。component
在類名上加上註解@componentxml
@Component(「user」) public class User { private int id; private String name; private Book book; //省略get set方法.... }
@Component後面參數爲該bean 的id。htm
spring-framework-3.2.4 版能夠經過在set方法前加上@Value註解爲相應屬性設置初值,以下:blog
@Value("張三") public void setName(String name) { this.name = name; }