首先要知道另一个东西,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. LinuxC++开发记录(g++)

    g++使用 1. 编译过程 预处理(-E) 编译(-S) 汇编(-c) 链接 1.1 预处理(-E) 为了直观的了解预处理,理解预处理做了哪些工作,不说那么多,直接上代码,创建main.h与main. ...

  2. goweb-go语言基础

    go语言基础 虽然这本书是讲goweb,但还是吧go语言基础过了一遍,由于我之前已经对go语言基础做了一遍系统的学习,这里就当简单回顾一下,不再写过多笔记了,之前的写的博客都有基础知识,O(∩_∩)O ...

  3. vim中的正则表达式替换

    这个总结的不错 http://tanqisen.github.io/blog/2013/01/13/vim-search-replace-regex/

  4. elasticsearch-hadoop 扩展定制 官方包以支持 update upsert doc

    官方源码地址https://github.com/elastic/elasticsearch-hadoop 相关文档 https://www.elastic.co/guide/en/elasticse ...

  5. sd卡分区步骤

    1.将sd卡通过优盘插在电脑上 2.fdisk  /dev/sdb 3.   m   //帮助 d    //删除分区 4.  n   //添加新的分区. p  //默认主分区 回车 +400M   ...

  6. php面向对象理解(一)

    常用的继承过程,以及对public.private.protected修饰符的理解: /*****************************父类************************* ...

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

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

  8. Docker相关学习地址

    菜鸟教程:http://www.runoob.com/docker/docker-image-usage.html 官方文档:https://docs.docker.com/

  9. SpringBoot集成ssm-druid-通用mapper

    简单介绍 springboot 首先什么是springboot? springboot是spring的另外一款框架,设计目的是用来简化新的spring应用的搭建和开发时所需要的特定的配置,从而使开发过 ...

  10. Codeforces Round #576 (Div. 2) D. Welfare State

    http://codeforces.com/contest/1199/problem/D Examples input1 output1 input2 output2 Note In the firs ...