spring @Primary @Autowired @Qualifier註解
阿新 • • 發佈:2018-12-12
當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,不會強制注入。