1、@Bean 與@Qualifier 區別
@Qualifier用於根據bean名稱指定注入bean時匹配的Bean
@Bean用於在配置類中聲明一個bean @Bean("bean"),可以指定bean名稱
轉載示例如下:
(1)創建一個名叫 ApplicationConfig 的類:
—> 1、用 @Configuration 注解上
—> 2、繼承 WebMvcConfigurerAdapter (零 XML 注入)
—> 3、定義一個方法用 @Bean 注解在此方法上
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; @Configuration public class ApplicationConfig extends WebMvcConfigurerAdapter { @Bean("testInterface") public TestInterface testInterface() { return new TestInterfaceImpl();
然后,在 Controller 或 ServiceImpl 層 就可直接用 @Autowired & @Qualifier 注入了:
—> @Bean("…") 必須與 @Qualifier("…") 括號里面的值必須一樣
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @RestController @RequestMapping("/test") public class CsMcmsErrorMessageController { @Autowired @Qualifier("testInterface") private TestInterface testInterface; }
2、@PrimaryKey 和@Qualifier區別
@Primary:在眾多相同的bean中,優先選擇用@Primary注解的bean(該注解加在各個bean上),但是不具有靈活性
@Qualifier:在眾多相同的bean中,@Qualifier指定需要注入的bean(該注解跟隨在@Autowired后),靈活性強。
參考資料:
1、史上最簡單SpringBoot @Bean & @Qualifier 注入(零 XML 注入)
2、Spring中@Primary和@Qualifier注解的區別