首先要知道另一个东西,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的用法实例的更多相关文章

  1. Spring通过注解@Autowired/@Resource获取bean实例时为什么可以直接获取接口而不是注入的类

    问: 这个问题困扰了我好久,一直疑问这个接口的bean是怎么注入进去的?因为只看到使用@Service注入了实现类serviceImpl,使用时怎么却获取的接口,而且还能调用到实现类的方法,难道这个接 ...

  2. @Autowired & @Resource 区别 & 解读@Bean

    一样     Autowired & @Resource 都可以用来Bean的注入,可以写在属性(字段)上.也可以写在setter方法上 不一样 1.来源不一样 @Autowired 由Spr ...

  3. @Autowired @Resource @Qualifier的区别

    参考博文: http://www.cnblogs.com/happyyang/articles/3553687.html http://blog.csdn.net/revent/article/det ...

  4. php中的curl使用入门教程和常见用法实例

    摘要: [目录] php中的curl使用入门教程和常见用法实例 一.curl的优势 二.curl的简单使用步骤 三.错误处理 四.获取curl请求的具体信息 五.使用curl发送post请求 六.文件 ...

  5. 上传文件及$_FILES的用法实例

    Session变量($_SESSION):�php的SESSION函数产生的数据,都以超全局变量的方式,存放在$_SESSION变量中.1.Session简介SESSION也称为会话期,其是存储在服务 ...

  6. C++语言中cin cin.getline cin.get getline gets getchar 的用法实例

    #include <iostream> #include <string> using namespace std; //关于cin cin.getline cin.get g ...

  7. Union all的用法实例sql

    ---Union all的用法实例sqlSELECT TOP (100) PERCENT ID, bid_user_id, UserName, amount, createtime, borrowTy ...

  8. 【转】javascript入门系列演示·三种弹出对话框的用法实例

    对话框有三种 1:只是提醒,不能对脚本产生任何改变: 2:一般用于确认,返回 true 或者 false ,所以可以轻松用于 if...else...判断 3: 一个带输入的对话框,可以返回用户填入的 ...

  9. php strpos 用法实例教程

    定义和用法该strpos ( )函数返回的立场,首次出现了一系列内部其他字串. 如果字符串是没有发现,此功能返回FALSE . 语法 strpos(string,find,start) Paramet ...

随机推荐

  1. pyQt 流布局的一个例子

    瀑布流布局 from PyQt5.QtCore import QPoint, QRect, QSize, Qt from PyQt5.QtWidgets import (QApplication, Q ...

  2. 吴裕雄--天生自然TensorFlow2教程:创建Tensor

    import numpy as np import tensorflow as tf tf.convert_to_tensor(np.ones([2, 3])) tf.convert_to_tenso ...

  3. UML-SSD总结

    1.不是所有场景都需要画SSD.需要画SSD的场景: 1).主成功场景 2).频繁发生的场景 3).复杂的场景 2.角色 1).参与者 2).系统(没有类,即黑盒) 3.画SSD时间不要过长,一般几分 ...

  4. [YNOI2018]五彩斑斓的世界&CF896E(分块+并查集)

    由于晚上比赛二连(Atcoder&codeforces),外加复习学考,所以暂时没时间写了. 贴个O(n√n)的分块代码,洛谷和cf上都过了,但垃圾bzoj卡不过去,不改了. #include ...

  5. 测试mvn -v 时报错,原因

    当安装完maven后在cmd命令框通过mvn -v 可以判断maven环境变量是否安装成功,但我安装配置完环境变量后执行报错如图 原因:配置的jdk的环境变量不符合maven最低要求(我配置的是jdk ...

  6. Python笔记_第二篇_面向过程_第二部分_3.模块的概述

    这部分内容是非常重要的,分模块的基本概念和一些常用模块的使用,其实常用模块使用这部分也不是太全面,后续或者有机会再通过其他材料进行讲解. 1. 模块的概述: 目前代码比较少,写在一个文件中还体现不出什 ...

  7. ILSVRC2012下载

    http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_img_test.tarhttp://www.image-net.or ...

  8. python文件读写 文件修改

    #设置一个变量f为文件对象,并打开文件#写文件#f = open('user.txt','w',encoding='utf-8') #f是一个文件对象f=open(r'c:\Users\PL\Desk ...

  9. 分布式ID的简单总结

    来源:郴州网站优化 简单总结一下流行的分布式id的实现方法 雪花算法 snowflake是twitter开源的分布式ID生成算法. 核心思想是:分布式ID固定是一个long型的数字,一个long型占8 ...

  10. MySQL修改最大连接数的两个方法,偏爱第一种

    总结MySQL修改最大连接数的两个方式   最大连接数是可以通过mysql进行修改的,mysql数据库修改最大连接数常用有两种方法,今天我们分析一下这两种方法之间的特点和区别,以便我们能更好的去维护m ...