http://tom-seed.iteye.com/blog/1584632
Spring注解方式bean容器管理
1.通過在配置文件中配置spring組件注入
- <context:component-scan base-package="com"/><!---通過該語句可以搜索com及com下子包中的類->
- <mvc:annotation-driven/>
2.為Spring編寫簡單bean類,一般對應接口與具體實現類
例如:
a.在com包下建立如下接口:HessianHelloWorld
b.com.impl包下新建如下實現類:HessianHelloWorldImpl
3.在此處使用注解形式進行來支持bean的管理
在具體需要托管的bean的類名上添加注解:@Controller
完整代碼如下:
- @Controller
- public class HessianHelloWorldImpl implements HessianHelloWorld{}
4.在業務類中調用上面的托管bean,以動態代理的形式引入;
private HessianHelloWorld hello;
並在屬性上添加注解
@Autowired
完整代碼如下:
- @Autowired
- private HessianHelloWorld hello;
注解方式結束
Spring配置文件形式:
1.去除上面的所有注解
在Spring配置文件中添加類的配置
- <bean id="hessianHelloWorldImpl" class="com.impl.HessianHelloWorldImpl"></bean>
2.在Spring配置文件中添加業務類的配置
業務類名為Test,在業務類中配置屬性(helloworld)及屬性指向托管bean的id,其中屬性helloworld在業務類中命名必須一致,且有該屬性的get/set方法
- <bean id="test" class="com.test.Test">
- <property name="helloWorld" ref="hessianHelloWorldImpl"></property>
- </bean>
3.在Test.java中添加
private HessianHelloWorld helloWorld;
與get/set方法
- private HessianHelloWorld helloWorld;
- public HessianHelloWorld getHelloWorld() {
- return helloWorld;
- }
- public void setHelloWorld(HessianHelloWorld helloWorld) {
- this.helloWorld = helloWorld;
- }
配置文件方式結束
注意事項
在此過程中需要注意注解方式與配置文件配置方式混合使用(由於業務需求的不同,例如注解方式的情況下使用定時器時就存在混合使用的情況)時的命名規范,當使用注解方式時bean在spring bean容器中的id首字母小寫的類全名,而通過配置文件配置時id為自定義。
如下實例為同時使用了注解方式與配置方式:
1.在spring配置文件中添加如下配置:
- <bean id="helloWorld" class="com.impl.HessianHelloWorldImpl" />
2.在托管bean(HessianHelloWorldImpl)上添加注解
- @Controller
- public class HessianHelloWorldImpl implements HessianHelloWorld{}
這樣HessianHelloWorldImpl在Spring的bean容器中注冊了兩個實例。即(helloWorld與hessianHelloWorldImpl)
3.在業務類(調用類)的屬性上添加標注,即不通過在配置文件中配置hello對應的類,而通過標簽自動匹配。
- @Autowired
- private HessianHelloWorld hello;
啟動時會報
- nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
- No unique bean of type [com.HessianHelloWorld] is defined:
- expected single matching bean but found 2: [helloWorld, hessianHelloWorldImpl]
由於此處的指針名為hello,通過自動匹配的方式無法確認具體需要用到哪個實例
在混用的情況下需要對bean實例的命名與bean的名稱管理。
上述情況不使用@Controller,直接在配置文件中注冊bean(bean的id不為hello),即一個bean在配置文件中注冊了兩次。
- <bean id="hessianHelloWorldImpl" class="com.remote.impl.HessianHelloWorldImpl"></bean>
也會出現同樣的效果。
如果必須使用混用,可以在業務類(調用類)的屬性名與bean容器中的名稱相同
- @Autowired
- private HessianHelloWorld helloWorld;
或者去除@Autowired直接在spring的bean配置文件中指定業務類屬性對應的實例名稱
- <bean id="test" class="com.test.Test">
- <property name="hello" ref="hessianHelloWorldImpl"></property>
- </bean>
常見錯誤:
通過配置文件配置bean的使用時
項目啟動時報錯:
- Cannot resolve reference to bean 'hessianHelloWorldImpl' while setting bean property 'hello';
- nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
- No bean named 'hessianHelloWorldImpl' is defined
spring找不到該類名,需要檢查spring配置文件中bean的配置,若使用標注的則需要檢查
<context:component-scan base-package="com"/>
<mvc:annotation-driven/>
是否已經添加
當業務調用類中使用標簽時(@Autowired),可能在啟動時不會報錯,但是調用時會出現空指針異常,也可能是因為和上面的情況一樣未指定bean的緣故