首先要知道另一个东西,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. JS用例

    showBtn :class="{getInput:showBtn}"v-if="showBtn" showBtn: true, this.showBtn = ...

  2. 基因调控网络 (Gene Regulatory Network) 01

    本文为入门级的基因调控网络文章,主要介绍一些基本概念及常见的GRN模型. 概念:基因调控网络 (Gene Regulatory Network, GRN),简称调控网络,指细胞内或一个基因组内基因和基 ...

  3. 结点选择(树形DP)

    Description 有一棵 n 个节点的树,树上每个节点都有一个正整数权值.如果一个点被选择了,那么在树上和它相邻的点都不能被选择.求选出的点的权值和最大是多少? Input 接下来的一行包含 n ...

  4. EXCEL启动慢

    启动太慢,一般是加载项的问题. 1.点击文件-EXCEL选项 2. 找到加载项,一般是COM加载项 3.选择com加载项 4.然后我出现了无法更改的情况,于是,我做了以下调整,进入office安装目录 ...

  5. 跨站脚本(XSS)攻击

    https://blog.csdn.net/extremebingo/article/details/81176394

  6. 吴裕雄--天生自然 PHP开发学习:表单 - 必需字段

    <?php // 定义变量并默认设为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $ema ...

  7. HTTP、MQTT、WebSocket有什么区别

    https://blog.csdn.net/linyunping/article/details/81950185 相同点:均为OSI 7层模型(应用层.表示层.会话层.传输层.网络层.数据链路层.物 ...

  8. Pmw大控件

    Python大控件——Pmw——是合成的控件,以Tkinter控件为基类,是完全在Python内写的.它们可以很方便地增加功能性的应用,而不必写一堆代码.特别是,组合框和内部确认计划的输入字段放在一起 ...

  9. Java之多线程窗口卖票问题(Runnable)

    /** * 例子:创建三个窗口卖票,总票数为100张.使用实现Runnable接口的方式 * 存在线程的安全问题,待解决. */class Window1 implements Runnable{ p ...

  10. 谷歌为何要研发新系统在5年内取代Android?

    现在的Android系统已经越做越好,体验也愈来愈佳,是唯一能和iOS掰腕子的移动操作系统.而且对于很多智能手机厂商来说,开源的Android为它们节约了太多成本,是不可或缺的基石之一.因此,想必很多 ...