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将被默认注入。

  • 相关阅读:
    思考
    创建Windows Mobile上兼容性好的UI 程序
    中文乱码(二)
    中文乱码(三)
    MySQL字符集产生乱码的简单讲解
    MySql乱码解决(五)
    中文乱码(四)
    mysql中文问题全处理
    Linux 中 x86 的内联汇编
    arm下的gcc内联汇编
  • 原文地址:https://www.cnblogs.com/silenceshining/p/15032714.html
Copyright © 2011-2022 走看看