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

  • 相关阅读:
    一个分油的逻辑问題C#实现
    vmware ESXI安装megacli
    搜索引擎Constellio及Google Search Appliances connectors
    MySQL 数据库性能优化之索引优化
    MySQL 数据库性能优化之缓存参数优化
    MySQL 数据库性能优化之表结构优化
    Spring中的WebAppRootListener
    MySQL 数据库性能优化之SQL优化
    8 个基于 Lucene 的开源搜索引擎推荐
    Spring 用户身份验证
  • 原文地址:https://www.cnblogs.com/silenceshining/p/15032714.html
Copyright © 2011-2022 走看看