当spring中管理两个类型一样的bean时,再进行注入时会报错:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.xhx.spring.Spring5AutowiredQualifierApplicationTests': Unsatisfied dependency expressed through field 'user3'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.xhx.spring.domain.User' available: expected single matching bean but found 2: user1,getUser2
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
看下面代码,@Primary表示当遇到系统中有两个User类型时,优先使用@Primary注解的这个进行注入。
package com.xhx.spring.config;
import com.xhx.spring.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class UserConfig {
@Bean(name = "user1")
public User getUser1(){
return new User("a23-fsa-ef","xu",25);
}
@Primary
@Bean(name = "user2")
public User user2(){
return new User("brr-dfa-874","haixing",25);
}
}
看下面测试代码:
package com.xhx.spring;
import com.xhx.spring.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Spring5AutowiredQualifierApplicationTests {
@Autowired(required = false) //一般在开发环境,不确定是否能注入时用
private User user1;
@Autowired
@Qualifier(value = "user1")
private User user2;
@Autowired
private User user3;
@Test
public void testAuto() {
System.out.println(user2.getName());
System.out.println(user1.getName());
System.out.println(user3.getName());
}
}
@Autowired:spring中有两种注入方式,by type/by name,@Autowired使用byType注入,当出现两个类型一样的时候,可以显示的用@Qualifier指定名称,表明用by name方式进行注入。否则会注入@Primary那个类。如果没有指定则会报错。 当不确定系统中是否能注入时,可以使用required=false,不会强制注入。
**实时内容请关注微信公众号,公众号与博客同时更新:程序员星星**