首先要知道另一个东西,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. POJ 2976 Dropping tests【0/1分数规划模板】

    传送门:http://poj.org/problem?id=2976 题意:给出组和,去掉对数据,使得的总和除以的总和最大. 思路:0/1分数规划 设,则(其中等于0或1) 开始假设使得上式成立,将从 ...

  2. KVM---虚拟机网络管理

    在上篇博客中我们完成了 KVM 虚机的安装,但是我发现虚机内的网络是不通的(当然了,在写这篇博客的时候已经把上篇博客中的配置文件修改好了,网络也是通的了,嘻嘻),所以这篇博客总结了一下虚机的网络连接方 ...

  3. cookie保存

    <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8 ...

  4. [mark]C# 异常处理

    https://docs.microsoft.com/zh-cn/dotnet/articles/csharp/programming-guide/exceptions/index

  5. 关于JavaWeb中Servlet的总结

    Servlet知识结构图 Servlet是JavaWeb服务器端的程序,一般一个Servlet处理一种特定的请求.Servlet编写好后,需要指定其所处理的请求的请求路径,也可以认为Servlet是一 ...

  6. 如何判断Office是32位还是64位?

    对于持续学习VBA的老铁们,有必要了解Office的位数. 如果系统是32位的,则不需要判断Office位数了,因为只能安装32位Office. 下面只讨论64位系统中,Office的位数判断问题. ...

  7. 模仿u-boot的makefile结构

    u-boot(2014.04)是通过顶层makefile调用各子目录中的makefile来实现整个工程的编译的,实际上子目录的makefile是include进来的.这里仿照这种结构写个模板测试一下. ...

  8. 使用spark

    更新说明 免密码登录 for f in `cat ~/machines`; do scp .ssh/id_dsa.pub $f:~/ ssh $f "cat id_dsa.pub >& ...

  9. Django2.0——django-filter: TypeError at *** __init__() got an unexpected keyword argument 'name'

    在使用 Django2.0 版本的 Django Rest Framwork 时,Django DeBug 报错 django-filter: TypeError at *** __init__() ...

  10. 面试常见二叉树算法题集锦-Java实现

    1.求二叉树的深度或者说最大深度 /* ***1.求二叉树的深度或者说最大深度 */ public static int maxDepth(TreeNode root){ if(root==null) ...