我有一个像这样定义的java spring配置,
@Configuration
public class FirstConfiguration {
@Bean
FirstController firstController() {
return new FirstController(firstService());
}
@Bean
FirstService firstService() {
return new FirstServiceImpl(secondService());
}
}
现在这个配置中的bean依赖于像这样定义的SecondConfiguration,
@Configuration
public class SecondConfiguration {
@Bean
SecondController SecondController() {
return new SecondController(SecondService());
}
@Bean
SecondService secondService() {
return new SecondServiceImpl();
}
}
如何在FirstConfiguration中使用secondService()bean?
答案 0 :(得分:2)
由于SecondService
是一个bean,你可以将它注入firstService
方法来配置另一个bean:
@Bean
FirstService firstService(@Autowired SecondService secondService) {
return new FirstServiceImpl(secondService);
}
答案 1 :(得分:1)
您可以像这样注入firstService
:
@Autowired
SecondService secondService
答案 2 :(得分:0)
导入配置时,可以直接引用方法secondService()
。
@Configuration
@Import(SecondConfiguration.class)
public class FirstConfiguration {
@Bean
FirstController firstController() {
return new FirstController(firstService());
}
@Bean
SomeController someController() {
return new SomeController(secondService());
}
}