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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值