zoukankan      html  css  js  c++  java
  • Spring中@Primary的应用

    首先看一下在Spring中这个注解的解释

     Indicates that a bean should be given preference when multiple candidates
     are qualified to autowire a single-valued dependency. If exactly one
     'primary' bean exists among the candidates, it will be the autowired value.

    意思是:当注入了多个符合条件的bean时,被@Primary注解的bean将作为默认的注入被使用。

    下面看一个例子:

    package com.springDemodemo.primaryDemo;
    
    public interface ITest {
    
         String test();
    }

    ITest接口的实现一,带Primary注解:

    package com.springDemodemo.primaryDemo;
    
    import org.springframework.context.annotation.Primary;
    import org.springframework.stereotype.Service;
    
    @Primary
    @Service
    public class TestDemo1 implements ITest{
        @Override
        public String test() {
            return "hello";
        }
    }

    ITest接口的实现二,不带Primary注解:

    package com.springDemodemo.primaryDemo;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class TestDemo2 implements ITest {
        @Override
        public String test() {
            return "world";
        }
    }

    测试,取出ITest接口的默认实现:

    package com.springDemodemo;
    
    import com.springDemodemo.primaryDemo.ITest;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.ApplicationContext;
    
    @SpringBootTest
    public class PrimaryTest {
    
        @Autowired
        ApplicationContext context;
    
        @Test
        public void test(){
            ITest bean = context.getBean(ITest.class);
            System.out.println(bean);
            System.out.println(bean.test());
        }
    
    }

    打印结果如下:

    com.springDemodemo.primaryDemo.TestDemo1@34cf294c
    hello

    结论:当有多个符合条件的bean时,@Primary注解的bean将被默认注入。

  • 相关阅读:
    day14(xml 编写及解析)
    day11(多线程,唤醒机制,生产消费者模式,多线程的生命周期)
    day13(反射,BeanUtils包)
    day10(IO流汇总)
    day08(File类 ,字节流)
    day08(异常处理,创建异常,finally,throws和throw的区别)
    [SPOJ-PT07J] Query on tree III (主席树)
    [ZJOI2008] 树的统计(树链剖分)
    长链剖分学习笔记
    [BZOJ4260] Codechef REBXOR (01字典树,异或前缀和)
  • 原文地址:https://www.cnblogs.com/silenceshining/p/15032714.html
Copyright © 2011-2022 走看看