如何使用多个弹簧配置文件

时间:2017-06-13 07:47:17

标签: java spring spring-mvc

我有一个像这样定义的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?

3 个答案:

答案 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());
    }
}

Refer the Spring config import

相关问题