2015-12-11 102 views
0

我在Spring中實現了抽象DAO工廠。Spring中靜態JdbcTemplate的替代方案

我有兩個自動裝配Autowired方法如下:

private DataSource dataSource; 
private JdbcTemplate jdbcTemplate; 

@Autowired 

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { 

    this.jdbcTemplate = jdbcTemplate; 
} 


@Autowired 

public void setDataSource(DataSource dataSource) { 
    this.dataSource = dataSource; 
} 

在開始使用的JdbcTemplate和數據源得到他們正確的價值觀。但是當我使用new關鍵字調用類的構造函數時,其中寫入了上述方法,jdbcTemplate和dataSource被設置爲NULL。

但是,如果我聲明它們是靜態的,那麼之前的右值將被保留。

我想知道如果我想保留上述兩個值的前面的值,是否還有其他靜態替代方法?

+0

你不應該使用新獲得Spring組件。這是錯誤的。你應該使用依賴注入,這就是Spring的全部內容。 –

+0

如果您創建jdbcTemplate和dataSource字段@Autowired,那麼spring將管理這些對象的生命週期。你不應該創建封閉類的實例。 – akki

回答

0

你應該在你的類的@Component上獲取dataSource和jdbcTemplate的對象值。您不應該使用類的新關鍵字來獲取自動裝配參考。

下面的代碼可能有助於你的問題。

import javax.sql.DataSource; 

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.jdbc.core.JdbcTemplate; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 

@Configuration 
@ComponentScan("com.ledara.demo") 
public class ApplicationConfig { 

    @Bean 
    public DataSource getDataSource() { 
     DriverManagerDataSource dmds = new DriverManagerDataSource(); 
     dmds.setDriverClassName("com.mysql.jdbc.Driver"); 
     dmds.setUrl("yourdburl"); 
     dmds.setUsername("yourdbusername"); 
     dmds.setPassword("yourpassword"); 
     return dmds; 
    } 

    @Bean 
    public JdbcTemplate getJdbcTemplate() { 
     JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource()); 
     return jdbcTemplate; 
    } 

} 

及以下類已自動連接的JdbcTemplate和數據源

import javax.sql.DataSource; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.jdbc.core.JdbcTemplate; 
import org.springframework.stereotype.Component; 
@Component 
public class SampleInfo{ 

    @Autowired(required=true) 
    DataSource getDataSource; 

    @Autowired(required=true) 
    JdbcTemplate getJdbcTemplate; 

    public void callInfo() { 
     System.out.println(getDataSource); 
     System.out.println(getJdbcTemplate); 

    } 

} 

的領域和下面是主類

public class MainInfo { 

    public static void main(String[] args) { 
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 
     context.register(ApplicationConfig.class); 
     context.refresh(); 
     SampleInfo si=context.getBean(SampleInfo.class); 
     si.callInfo(); 
    } 

}