Spring依赖注入之Annotation_Autowired和Qualifier

使用Spring的注解,必须在xml的头必须如下:
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 7            http://www.springframework.org/schema/context
 8            http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 9                
10      <context:annotation-config/>
11      
12 </beans>


@Autowired的用法:
@Autowired是Spring.jar文件里面的内容,一般注解在set方法上,是通过ByType方式注入的
Java代码如下:

1     @Autowired
2     public void setBookDAO(BookDAO bookDAO) {
3         System.out.println("******************setBookDAO");
4         this.bookDAO = bookDAO;
5         System.out.println(this.bookDAO.getClass().toString());        
6     }


xml文件如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 7            http://www.springframework.org/schema/context
 8            http://www.springframework.org/schema/context/spring-context-2.5.xsd">          
 9        <context:annotation-config></context:annotation-config>
10 
11   <bean id="BookDAOImpl" class="com.test.dao.impl.BookDAOImpl">
12     
13   </bean>

如果xml文件有多个同一类型的bean标签,可以采用@Qualifier进行制定注入哪一个bean

1      @Autowired
2      public void setBookDAO(@Qualifier("BookDAOImpl")BookDAO bookDAO) {
3         System.out.println("******************setBookDAO");
4         this.bookDAO = bookDAO;
5         System.out.println(this.bookDAO.getClass().toString());        
6      }
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"  
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 7            http://www.springframework.org/schema/context
 8            http://www.springframework.org/schema/context/spring-context-2.5.xsd">          
 9        <context:annotation-config></context:annotation-config>
10 
11   <bean id="BookDAOImpl" class="com.test.dao.impl.BookDAOImpl">
12     
13   </bean>
14   
15   <bean id="BookDAOImpl1" class="com.test.dao.impl.BookDAOImpl">
16     
17   </bean>
18   
19   <!-- more bean definitions go here -->
20 
21 </beans>

 

posted on 2015-08-10 12:25  nuosiboy  阅读(166)  评论(0编辑  收藏  举报

导航