Spring Annotation(注解) Autowired Qualifier


 @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());
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值