2016-01-21 96 views
0

在我的Spring配置類中,我需要jdbcTemplate來初始化其他bean。在配置類本身初始化的spring配置類中使用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. 

} 
+3

只需將其添加爲方法參數'someDatabaseTableValues(JdbcTemplate template)'。 –

+0

使用'@DependsOn(「jdbcTemplate」)'而不是'@ Lazy'並調用JdbcTemplate jdbcTemplate = jdbcTemplate(); ''在你的'someDatabaseTableValues()'方法中。第一個註解保證jdbcTemplate bean在初始化'someDatabaseTableValues()'之前被初始化。跳過'@ DependsOn'可能會導致循環引用異常。除此之外,爲bean命名總是安全的,即'@Bean(name =「jdbcTemplate」)...' –

回答

1

使用方法如下:

@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()註解在自動裝配Autowired方法參數的前面做同樣的bean類型的多個實例加以區分。

注意,你也可以使用JSR-250@ResourceJSR-330@Inject註釋,而不是@Autowired,因爲這些都是由Spring支持的爲好。