繁体   English   中英

在spring配置类中使用在配置类本身中初始化过的bean

[英]Use a bean in spring configuration class which initialized in the configuration class itself

在我的Spring Configuration类中,我需要jdbcTemplate来初始化其他bean。

@Configuration
public class ApplicationBeansConfiguration {
    @Bean
    public JdbcTemplate jdbcTemplate() throws GeneralSecurityException {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
        return jdbcTemplate;
    }

    @Bean
    @Lazy 
    public Map<String, String> someDatabaseTableValues(){
    // I need jdbcTemplate bean here.

}

像这样使用它:

@Bean
@Lazy 
public Map<String, String> someDatabaseTableValues() {
    //the following JdbcTemplate instance will already be configured by Spring
    JdbcTemplate template = jdbcTemplate();
    ...
}

一些解释:Spring需要CGLIB进行@Configuration类处理。 它可以有效地使CGLIB代理脱离您的配置类。 在配置类上调用@Bean方法时,它将由CGLIB代理处理。 代理拦截器将检查是否已经有可用的bean实例(对于单例bean),并返回该缓存实例。 如果没有缓存的实例,它将调用您的@Bean工厂方法并应用任何配置,并对应用程序上下文设置为进行后处理。 返回时,它将在需要时缓存Bean实例(再次针对单例Bean),并将配置的Bean实例返回给您。

您还可以将方法注入与@Autowired

@Autowired
@Bean
@Lazy 
public Map<String, String> someDatabaseTableValues(JdbcTemplate template) {
    ...
}

您可以在自动装配的方法前面使用@Qualifier()注释,以区分相同bean类型的多个实例。

请注意,您还可以使用JSR-250@ResourceJSR-330@Inject注释代替@Autowired ,因为Spring也支持它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM