首先看一下在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将被默认注入。