springboot 构造注入实例
所属分类 springboot
浏览量 1022
消除歧义
@Primary @Qualifier
public TestBean TestBean(@Qualifier("springInfoBean2") SpringInfoBean bean)
bean之间依赖
// springInfoBean2 依赖 springInfoBean
@DependsOn("springInfoBean")
@Bean("springInfoBean2")
public SpringInfoBean springInfoBean2(ApplicationContext ctx){
return new SpringInfoBean("springInfoBean2");
}
@Configuration
public class ConstructInjectConfig {
// Parameter 0 of method TestBean in demo.config.ConstructInjectConfig required a single bean, but 2 were found
// Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
// @Primary @Qualifier
// @Qualifier("springInfoBean2") SpringInfoBean bean
//
@Bean
public TestBean TestBean(@Qualifier("springInfoBean2") SpringInfoBean bean)throws Exception{
String msg = "ConstructInjectConfig.TestBean.bean="+bean.getId();
System.out.println(msg);
MsgUtil.add(msg);
Thread.sleep(2000);
return new TestBean(bean);
}
}
@Configuration
public class TestConfig {
// Springboot注入ApplicationContext的几种方式 http://codefun007.xyz/a/article_detail/1173.htm
//// 方法参数的 environment 和 ApplicationContext 会自动注入
// @Primary
@Bean("springInfoBean")
public SpringInfoBean springInfoBean(Environment environment){
return new SpringInfoBean("springInfoBean");
}
@Bean("springInfoBean2")
@DependsOn("springInfoBean")
public SpringInfoBean springInfoBean2(ApplicationContext ctx){
return new SpringInfoBean("springInfoBean2");
}
}
完整例子代码
https://gitee.com/dyyx/springboothello/blob/master/src/main/java/demo/config/ConstructInjectConfig.java
spring构造注入优缺点
Springboot注入ApplicationContext的几种方式
上一篇
下一篇
kafka命令行发送接收消息
zookeeper命令行zkCli使用
spring构造注入优缺点
zookeeper配置参数
dubbo面试题
ZooKeeper面试题