IOC @Autowired/@Resource/@Qulified的用法实例
首先要知道另一个东西,default-autowire,它是在xml文件中进行配置的,可以设置为byName、byType、constructor和autodetect;比如byName,不用显式的在bean中写出依赖的对象,它会自动的匹配其它bean中id名与本bean的set**相同的,并自动装载。
@Autowired是用在JavaBean中的注解,通过byType形式,用来给指定的字段或方法注入所需的外部资源。
两者的功能是一样的,就是能减少或者消除属性或构造器参数的设置,只是配置地方不一样而已。
autowire四种模式的区别:

@Autowired 可以作用在
- 成员变量
- 成员方法
- 构造方法
--------------------------------------------@Autowired用在成员变量上面-------------------------------------
1. 创建一个接口IUserDao
package com.longteng.service.Imple;
public interface IUserDao {
public String addUserName(String name);
//public Map<String,String> getUserByName(String name);
}
2. 创建IUserDao的实现类UserDao
package com.longteng.service.Imple; import org.springframework.stereotype.Repository; @Repository
public class UserDao implements IUserDao { @Override
public String addUserName(String name) {
return name+"添加成功了";
}
}
3 . 创建IUserDao的实现类AnotherUserDao
package com.longteng.lesson2.dao.impl; import com.longteng.lesson2.dao.IOrderDao;
import org.springframework.stereotype.Repository; @Repository
public class AnotherOrderDao implements IOrderDao {
@Override
public String bookOrder(String name) {
return null;
}
}
4、 创建OrderService
package com.longteng.lesson2.service;
import com.longteng.lesson2.dao.IOrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; @Service
public class OrderService { @Autowired
IOrderDao iOrderDao; public String getOrderInfo(String name){
return iOrderDao.bookOrder(name);
}
@PostConstruct
public void initTest(){
System.out.println("初始化调用方法");
}
@PreDestroy
public void tearDownTest(){
System.out.println("回收调用方法");
}
}
5、创建一个配置文件
package com.longteng.lesson2.config; import com.longteng.lesson2.service.OrderService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan(basePackages = {"com.longteng.lesson2.dao","com.longteng.lesson2.service"})
public class OrderCfg { @Bean
public OrderService getOrderService(){
return new OrderService();
}
}
6、创建测试类
package com.longteng.lesson2.dao; import com.longteng.lesson2.config.OrderCfg;
import com.longteng.lesson2.service.OrderService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class OrderDaoTest {
ApplicationContext context;
@Before
public void initApplication(){
context = new AnnotationConfigApplicationContext(OrderCfg.class);
}
@Test
public void test(){
OrderService orderService = context.getBean("orderService", OrderService.class);
System.out.println(orderService.getOrderInfo("zhou"));
Assert.assertEquals("成功了","zhou预订了订单",orderService.getOrderInfo("zhou"));
}
}
7 测试结果
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.longteng.lesson2.dao.IOrderDao' available: expected single matching bean but found : anotherOrderDao,orderDao
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:)
... more
8 解决办法
修改1
package com.longteng.lesson2.dao.impl; import com.longteng.lesson2.dao.IOrderDao;
import org.springframework.stereotype.Repository; @Repository("anotherOrderDao")
public class AnotherOrderDao implements IOrderDao {
@Override
public String bookOrder(String name) {
return null;
}
}
修改2
package com.longteng.lesson2.dao.impl; import com.longteng.lesson2.dao.IOrderDao;
import org.springframework.stereotype.Repository; @Repository("orderDao")
public class OrderDao implements IOrderDao {
@Override
public String bookOrder(String name) {
return name+"预订了订单";
}
}
修改3
package com.longteng.lesson2.service;
import com.longteng.lesson2.dao.IOrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; @Service
public class OrderService { @Autowired
@Qualifier("orderDao")
IOrderDao iOrderDao; public String getOrderInfo(String name){
return iOrderDao.bookOrder(name);
}
@PostConstruct
public void initTest(){
System.out.println("初始化调用方法");
}
@PreDestroy
public void tearDownTest(){
System.out.println("回收调用方法");
}
}
运行结果
初始化调用方法
::54.218 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'getOrderService'
::54.218 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
::54.239 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@f4ea7c]
::54.239 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
::54.241 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
::54.243 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'orderService'
zhou预订了订单
--------------------------------------------@Autowired用在成员方法上面-------------------------------------
1. 创建一个接口IUserDao
package com.longteng.service.Imple;
public interface IUserDao {
public String addUserName(String name);
//public Map<String,String> getUserByName(String name);
}
2. 创建IUserDao的实现类UserDao
package com.longteng.service.Imple; import org.springframework.stereotype.Repository; @Repository
public class UserDao implements IUserDao { @Override
public String addUserName(String name) {
return name+"添加成功了";
}
}
3 . 创建OrderService
package com.longteng.lesson2.service;
import com.longteng.lesson2.dao.IOrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; @Service
public class OrderService { IOrderDao iOrderDao;
@Autowired
public void setiOrderDao(IOrderDao iOrderDao) {
this.iOrderDao = iOrderDao;
} public String getOrderInfo(String name){
return iOrderDao.bookOrder(name);
}
@PostConstruct
public void initTest(){
System.out.println("初始化调用方法");
}
@PreDestroy
public void tearDownTest(){
System.out.println("回收调用方法");
}
}
4、创建一个配置文件
package com.longteng.lesson2.config; import com.longteng.lesson2.service.OrderService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan(basePackages = {"com.longteng.lesson2.dao","com.longteng.lesson2.service"})
public class OrderCfg { @Bean
public OrderService getOrderService(){
return new OrderService();
}
}
5、创建测试类
package com.longteng.lesson2.dao; import com.longteng.lesson2.config.OrderCfg;
import com.longteng.lesson2.service.OrderService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class OrderDaoTest {
ApplicationContext context;
@Before
public void initApplication(){
context = new AnnotationConfigApplicationContext(OrderCfg.class);
}
@Test
public void test(){
OrderService orderService = context.getBean("orderService", OrderService.class);
System.out.println(orderService.getOrderInfo("zhou"));
Assert.assertEquals("成功了","zhou预订了订单",orderService.getOrderInfo("zhou"));
}
}
6、运行结果
::27.880 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'getOrderService' to allow for resolving potential circular references
::27.880 [main] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected element of bean 'getOrderService': AutowiredMethodElement for public void com.longteng.lesson2.service.OrderService.setiOrderDao(com.longteng.lesson2.dao.IOrderDao)
::27.881 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'orderDao'
::27.881 [main] DEBUG org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'getOrderService' to bean named 'orderDao'
::27.881 [main] DEBUG org.springframework.context.annotation.CommonAnnotationBeanPostProcessor - Invoking init method on bean 'getOrderService': public void com.longteng.lesson2.service.OrderService.initTest()
初始化调用方法
::27.881 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'getOrderService'
::27.881 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
::27.902 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@e31a9a]
::27.902 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
::27.904 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
::27.906 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'orderService'
zhou预订了订单
IOC @Autowired/@Resource/@Qulified的用法实例的更多相关文章
- Spring通过注解@Autowired/@Resource获取bean实例时为什么可以直接获取接口而不是注入的类
问: 这个问题困扰了我好久,一直疑问这个接口的bean是怎么注入进去的?因为只看到使用@Service注入了实现类serviceImpl,使用时怎么却获取的接口,而且还能调用到实现类的方法,难道这个接 ...
- @Autowired & @Resource 区别 & 解读@Bean
一样 Autowired & @Resource 都可以用来Bean的注入,可以写在属性(字段)上.也可以写在setter方法上 不一样 1.来源不一样 @Autowired 由Spr ...
- @Autowired @Resource @Qualifier的区别
参考博文: http://www.cnblogs.com/happyyang/articles/3553687.html http://blog.csdn.net/revent/article/det ...
- php中的curl使用入门教程和常见用法实例
摘要: [目录] php中的curl使用入门教程和常见用法实例 一.curl的优势 二.curl的简单使用步骤 三.错误处理 四.获取curl请求的具体信息 五.使用curl发送post请求 六.文件 ...
- 上传文件及$_FILES的用法实例
Session变量($_SESSION):�php的SESSION函数产生的数据,都以超全局变量的方式,存放在$_SESSION变量中.1.Session简介SESSION也称为会话期,其是存储在服务 ...
- C++语言中cin cin.getline cin.get getline gets getchar 的用法实例
#include <iostream> #include <string> using namespace std; //关于cin cin.getline cin.get g ...
- Union all的用法实例sql
---Union all的用法实例sqlSELECT TOP (100) PERCENT ID, bid_user_id, UserName, amount, createtime, borrowTy ...
- 【转】javascript入门系列演示·三种弹出对话框的用法实例
对话框有三种 1:只是提醒,不能对脚本产生任何改变: 2:一般用于确认,返回 true 或者 false ,所以可以轻松用于 if...else...判断 3: 一个带输入的对话框,可以返回用户填入的 ...
- php strpos 用法实例教程
定义和用法该strpos ( )函数返回的立场,首次出现了一系列内部其他字串. 如果字符串是没有发现,此功能返回FALSE . 语法 strpos(string,find,start) Paramet ...
随机推荐
- vue多选验证
vue select 多选 验证 <FormItem :prop="'formList.'+index+'.name'" label="姓名" :rule ...
- 一维跳棋(BFS)
一维跳棋是一种在1×(2N+1) 的棋盘上玩的游戏.一共有N个棋子,其中N 个是黑的,N 个是白的.游戏开始前,N 个白棋子被放在一头,N 个黑棋子被放在另一头,中间的格子空着. 在这个游戏里有两种移 ...
- 吴裕雄--天生自然MySQL学习笔记:MySQL 管理
启动及关闭 MySQL 服务器 Windows 系统下 在 Windows 系统下,打开命令窗口(cmd),进入 MySQL 安装目录的 bin 目录. 启动: cd c:/mysql/bin mys ...
- Spring Cloud Hystrix熔断器隔离方案
Hystrix组件提供了两种隔离的解决方案:线程池隔离和信号量隔离.两种隔离方式都是限制对共享资源的并发访问量,线程在就绪状态.运行状态.阻塞状态.终止状态间转变时需要由操作系统调度,占用很大的性 ...
- PAT Basic 1023 组个最⼩数 (20) [贪⼼算法]
题目 给定数字0-9各若⼲个.你可以以任意顺序排列这些数字,但必须全部使⽤.⽬标是使得最后得到的数尽可能⼩(注意0不能做⾸位).例如:给定两个0,两个1,三个5,⼀个8,我们得到的最⼩的数就是1001 ...
- 求素数的一个快速算法 Python 快速输出素数算法
思想 以100以内为例. 生成一个全是True的101大小的数组 2开始,遇到2的倍数(4,6,8,10...)都赋值为False 因为这些数字都有因子 2 3开始,遇到3的倍数(6,9,12...) ...
- python 拆解包
Python 拆解包 转自:https://www.jianshu.com/p/22c538a58bcc python中的解包可以这样理解:一个list是一个整体,想把list中每个元素当成一个个个体 ...
- 2019牛客暑期多校训练营(第五场)B.generator 1
传送门:https://ac.nowcoder.com/acm/contest/885/B 题意:给出,由公式 求出 思路:没学过矩阵快速幂.题解说是矩阵快速幂,之后就学了一遍.(可以先去学一下矩阵快 ...
- python 多维数组 字典
#多维数组list = [[87,57,98],[34,87,90]]print(list[1][0]) l = [[87,57,98],[34,87,[90,99,67]]]print(l[1][2 ...
- html 基础笔记
html 1,一套规则,浏览器认识的规则 2,开发者: 学习Html规则 开发后台程序: -写Html文件(充当模板的作用) -数据库获取数据,然后替换到html文件的指定位置(web框架) 3,本地 ...