• 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 2: anotherOrderDao,orderDao
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
        ... 36 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("回收调用方法");
        }
    }

    运行结果

    初始化调用方法
    14:35:54.218 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'getOrderService'
    14:35:54.218 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
    14:35:54.239 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@f4ea7c]
    14:35:54.239 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
    14:35:54.241 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
    14:35: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、运行结果

    14:42:27.880 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'getOrderService' to allow for resolving potential circular references
    14:42: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)
    14:42:27.881 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'orderDao'
    14:42:27.881 [main] DEBUG org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'getOrderService' to bean named 'orderDao'
    14:42:27.881 [main] DEBUG org.springframework.context.annotation.CommonAnnotationBeanPostProcessor - Invoking init method on bean 'getOrderService': public void com.longteng.lesson2.service.OrderService.initTest()
    初始化调用方法
    14:42:27.881 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'getOrderService'
    14:42:27.881 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
    14:42:27.902 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@e31a9a]
    14:42:27.902 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
    14:42:27.904 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
    14:42:27.906 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'orderService'
    zhou预订了订单
  • 相关阅读:
    小知识点
    异常关机后idea的注入不能使用
    day42_mysql 数据库操作 数据库的约束
    day41_mysql安装与卸载 mysql配置 SQL语句 DDL:操作数据库,表 DML:增删改表中的记录 DQL:查询表中的记录 DCL:管理用户与授权
    day39_ECMAScript BOM DOM
    day38_JS
    day35_HTML inpot标签 form表单
    day33_Stream(JDK1.8后的接口,本身不是函数式接口)
    day32_ 优化文件上传及接收 函数式接口 自定义函数接口 函数式编程 常用函数式接口 Stream流
    day31_网络通信三要素 TCP Socket关键字 ServerSocket
  • 原文地址:https://www.cnblogs.com/zhou-test/p/10096420.html
Copyright © 2020-2023  润新知