您的位置:首页 > 编程语言 > Java开发

Spring Annotation(注解) Autowired Qualifier

2014-01-19 21:49 330 查看
 @Autowired 与@ qualifier

a)     默认按类型byType

b)     如果想用byName,使用@Qulifier

c)     写在private field(第三种注入形式)(不建议,破坏封装)

d)    
 @Autowired写在set上,@qualifier需要写在参数上




Spring注解:

在applicationContext.xml配置文件中进行如下配置:






代码:

<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<context:annotation-config></context:annotation-config>

<!--
两个一样类的bean,是为了@Qualifier("stuDao2") 注解可以以指定的bean名称进行注入
但是如果不是用@Qualifier("stuDao2")注解,而是用@Autowired注入 将报错 因为@Autowired注入默认是按
byType来注入,此时他不知道注入哪一个 因为都是class="com.mth.impl.StuDaoImpl"
-->
<bean id="stuDao1" class="com.mth.impl.StuDaoImpl"></bean>
<bean id="stuDao2" class="com.mth.impl.StuDaoImpl"></bean>
<bean id="ser" class="com.mth.service.Service"></bean>
</beans>


Service如下写注解:

package com.mth.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.mth.bean.Student;
import com.mth.dao.IStuDao;

public class Service {
private IStuDao dao;

public IStuDao getDao() {
return dao;
}

// 在set方法上面写@Autowired (默认是byType注入)
// @Qualifier("stuDao2") 指定从配置文件applicationContext.xml中按哪个名字的bean来注入
@Autowired
public void setDao(@Qualifier("stuDao2") IStuDao dao) {
this.dao = dao;
}

public void saveStu(Student student) {
dao.saveStu(student);
}

}


测试代码:

package com.mth.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mth.bean.Student;
import com.mth.service.Service;

public class Test {

/**
* @Title: main
* @Description: 测试Spring注解
* @param @param args 设定文件
* @return void 返回类型
* @throws
*/
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Service service = (Service) context.getBean("ser");
service.saveStu(new Student());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Autowire ioc spring xml bean