首页 > 代码库 > Spring Annotation(@Autowire、@Qualifier)

Spring Annotation(@Autowire、@Qualifier)

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xmlns:p="http://www.springframework.org/schema/p"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 8     
 9     <context:annotation-config />
10     <bean id="userDao" class="com.bxw.dao.impl.UserDaoImpl" />
11     <bean id="userService" class="com.bxw.service.UserService" lazy-init="true" scope="singleton" init-method="init" destroy-method="destroy"/>
12 
13 </beans>
applicationContext.xml

xmlns(xml命名空间):其实就是指定该xml的格式,能够用哪些标签。

需要添加xmlns:context="http://www.springframework.org/schema/context"

和xsi:schemaLocation中添加

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"

 

applicationContext.xml需要添加<context:annotation-config />,这会初始化4个用来处理一些注解的bean

 

技术分享
 1 package com.bxw.service;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Qualifier;
 5 
 6 import com.bxw.dao.UserDao;
 7 import com.bxw.dao.impl.UserDaoImpl;
 8 import com.bxw.po.User;
 9 
10 public class UserService {
11     private UserDao userDao = new UserDaoImpl();
12     
13     public void init() {
14         System.out.println("init...");
15     }
16     
17     public UserDao getUserDao() {
18         return userDao;
19     }
20 
21     @Autowired
22     public void setUserDao(@Qualifier("userDao") UserDao userDao) {
23         this.userDao = userDao;
24     }
25     
26     public void add(User u){
27         this.userDao.save(u);
28     }
29     
30     public void destroy() {
31         System.out.println("destroy...");
32     }
33     
34 }
UserService.java

@Autowire一般注解在set方法上,会采用bytype的方式注入(虽然它可以注解在各种方法甚至是成员变量上,但不常用)

采用bytype方式注入会发生一些问题,例如如果配置了名字(id)不同但class相同的两个bean,这个时候将会报错,采用@Qualifier解决。

@Qualifier可以在bean中进行配置,如果没有配置的且指定了该bean的id,则id值即为qualifier的默认值。(这也解释了UserService.java中为什么是@Qualifier("userDao")).

Spring Annotation(@Autowire、@Qualifier)