【发布时间】:2023-04-01 15:01:01
【问题描述】:
我有一个配置类,根据所选配置文件定义了两个 bean,并覆盖了配置方法:
@Configuration
class MyConfig {
@Profile("profile")
@Bean
MyBean myBean(MyBeanProperties properties) {
return new MyBean(properties);
}
@Profile("!profile")
@Bean
MyBean myBean(MyBeanProperties properties, AdditionalProperties addProps) {
MyBean result = new MyBean(properties);
result.addAdditionalProperties(addProps);
return result;
}
}
以及一个将MyBean 自动连接到其中的类
@Service
class MyService {
MyBean autowiredBean;
private MyService(MyBean bean) { this.autowiredBean = bean; }
}
现在,当我启动 Spring 上下文时,它会失败并显示消息
com.example.MyServce 中构造函数的参数 0 需要一个无法找到的“com.example.MyBean”类型的 bean。
这怎么可能?我清楚地定义了 Spring bean,因此它应该在创建上下文时出现。
【问题讨论】:
-
您可以创建两个不同的配置文件并在类级别指定配置文件。 github中的示例github.com/naveenkulkarni029/categories-api
@Profile以应用于Controller级别为例