spring @Bean @Qualifier @Primary

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注解的区别

猜你喜欢

转载自www.cnblogs.com/dancser/p/12660317.html