上1篇博客,學習了spring的依賴注入,即利用spring容器來為類中的屬性賦值,分為兩種賦值方法,利用set和利用構造方法,我們都知道,如果我需要為某1個屬性賦值的話,必須為該屬性寫上set方法,那末大家有無想過1個問題,如果我們1個類中有很多個屬性,我們會生成大量的set方法,如果用構造方法來賦值,即<constructor-arg index="" type="" ref="" value=""></constructor-arg>,這樣也會存在很多個這樣的標簽,由于1個<constructor-arg index="" type="" ref="" value=""></constructor-arg>只能為1個屬性賦值,為了解決這些困難,我們可以利用注解來為屬性進行賦值。
一樣,我們新建兩個類ClassInfo.java和Teacher.java
注意:由于我們使用注解來為屬性賦值的,所以我們需要導入命名空間,以下:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context⑵.5.xsd"
其次需要導入依賴注入的注解解析器:
<context:annotation-config></context:annotation-config>
3.導入需要被spring容器來管理的類。
經過上面漫步操作以后呢,applicationContext.xml是這個模樣:
this is classInfo....
這充分辯明了利用注解為Teacher類中的classInfo對象賦值成功了。在這里需要注意:如果我么你的@Resource的注解的值為"",那末spring將會將容器中id為該屬性的類注入給該屬性。甚么意思呢??我舉個栗子:
我將上面的@Resource的值修改成這樣:@Resource(name="test")此時由于name的值不是"",所以spring容器將不會試圖匹配與該屬性相同的id對應的類,而是將id為test的類注入給該屬性,但是,此時并沒有id為test的類,所以會拋出以下異常:
No bean named 'test' is defined
此時我將classInfo對應的id改成test,再次運行發現程序是ok的。
其實spring有自己定義的注解的,仔細的程序員可能發現了@Resource是java官方提供的1個注解,其實不是spring的,我們可以將@Resource替換成@Autowired,這個@Autowired是根據類型進行匹配的。那我如果非要依照id來進行匹配怎樣辦呢?別急,spring為我們提供了1個@Qualifier,我們如果要匹配spring容器中id為classInfo的類,可以這樣寫:@Qualifier("classInfo"),注意:這里還需要加上@Autowired,以下:
@Autowired
@Qualifier("classInfo")
private ClassInfo classInfo;
大家有無想過,既然spring是用來管理bean的,難道就沒有生命周期的管理???是有的。我們為ClassInfo類添加以下初始化和燒毀方法:
classInfo init....
this is classInfo....
classInfo destroy.....
我們發現確切履行了初始化和燒毀的方法,說明利用注解來實現聲明周期的管理也是可以的。
但是,注意spring的注解只能用于援用類型。
那我能不能在applicationContext.xml中對bean的聲明也不寫呢??是可以的,怎樣做的,一樣分為以下3步:
1.導入命名空間:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context⑵.5.xsd"
<context:annotation-config></context:annotation-config>
3.啟動依賴注入的注解解析器
<context:component-scan base-package="com.test.spring.di"></context:component-scan>
這里是掃描"com.test.spring.di"包和該包下的所有的類。
4.在需要被spring來管理的類上加上@Component的注解
注意:和@Resource比較相似,@Component是默許匹配類名的第1個字母小寫的,比如我在Teacher類上加了@Component這個注解,那末可以這樣得到該類對象:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/test/spring/di/applicationContext.xml");
Teacher teacher = (Teacher) applicationContext.getBean("teacher");
如果Teacher類上寫了這樣1個@Component("teacherId"),那末此時就需要通過
Teacher teacher = (Teacher) applicationContext.getBean("teacherId");
才可以得到Teacher對象。這里的@Component是1個比較寬泛的泛型,spring為我們提供了更詳細的注解配置:
@Controller 配置控制器的,控制視圖的跳轉
@Service 配置service的,不是android中的service
@Repository 配置dao的,控制操作數據庫的
我們發現這3個注解是對web開發中的MVC編程很好的1個支持。
恩,今天spring注解,就到這里吧,希望大家看了都能理解。
源碼下載
上一篇 poj 1988(并查集)
下一篇 vim編輯器替換功能詳解