工厂类在春天有数据库连接

时间:2014-06-03 02:32:34

标签: spring java-ee spring-mvc

我需要编写一个工厂类,调用数据库并将数据存储到静态对象中。我知道如何将其写为普通的java。但我不能在春天做。能够获得模式,但在调用“factory-method”时无法获得数据库连接。下面是代码

public class ApplicationSettingsDAO {

private static ApplicationSettingsDAO objSettings = null; // new ApplicationSettingsDAO();

@Autowired
private DataSource dataSource;

private ApplicationSettingsDAO() {
    getDBConncection();
}


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

public DataSource getDataSource() {
    return this.dataSource;
}

public static ApplicationSettingsDAO getInstance() {
    if (objSettings == null) {
        synchronized (ApplicationSettingsDAO.class) {
            if (objSettings == null) {
                objSettings = new ApplicationSettingsDAO();
            }
        }
    }
    return objSettings;
}

public void getDBConncection() {
    System.out.println("dataSource -> " + dataSource);
    try {
        Connection objConnection = dataSource.getConnection();
        PreparedStatement objPrepStatement = objConnection.prepareStatement("Select ApplicationSettingID, SettingID, Value From ApplicationSetting");
        ResultSet objResultSet =  objPrepStatement.executeQuery();
        while(objResultSet.next()) {
            System.out.println("--> " + objResultSet.getInt("SettingID") + " >> " + objResultSet.getString("Value"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

Bean配置

<bean id="objSettings" class="com.schoolcity.stars.dao.common.ApplicationSettingsDAO" factory-method="getInstance" >
    <property name="dataSource" ref="dataSource"/>
</bean>

无法在容器启动时获取dataSource对象。但如果我打电话

,它就有效
 ApplicationSettingsDAO.getInstance().getDBConncection();

我需要在调用getInstance()时调用getDBConncection()。

谢谢

0 个答案:

没有答案