你需要創建財產裝載機自己的自定義實現:
public class DbPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
private static final Logger LOG = LoggerFactory.getLogger(DbPlaceholderConfigurer.class);
public DbPlaceholderConfigurer(DataSource dataSource) {
try {
Map<String, Object> loadedSettings = loadProperties(dataSource);
MutablePropertySources mutablePropertySources = new MutablePropertySources();
mutablePropertySources.addFirst(new MapPropertySource("custom", loadedSettings));
setPropertySources(mutablePropertySources);
} catch (SQLException e) {
LOG.error("Error loading properties", e);
}
}
private Map<String, Object> loadProperties(DataSource dataSource) throws SQLException {
LOG.info("{}", dataSource);
Connection connection = dataSource.getConnection();
PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM Settings");
Map<String, Object> loadedSettings = new HashMap<String, Object>();
prepareStatement.execute();
ResultSet resultSet = prepareStatement.getResultSet();
while (resultSet.next()) {
loadedSettings.put(resultSet.getString(2), resultSet.getString(3));
}
connection.close();
return loadedSettings;
}
}
下面是配置類。以下給出HSQL,根據你的需要改變它,即。 mySql數據源。
@Configuration
@ComponentScan({ "package_name_to_scan" })
public class AppConfig {
private static final Logger LOG = LoggerFactory.getLogger(AppConfig.class);
private static EmbeddedDatabase dataSource;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new DbPlaceholderConfigurer(dataSource());
}
@Bean
public static DataSource dataSource() {
if(dataSource == null) {
EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
databaseBuilder.addScript("classpath:schema.sql");
databaseBuilder.setName("test");
databaseBuilder.setType(EmbeddedDatabaseType.HSQL);
EmbeddedDatabase build = databaseBuilder.build();
initPopulate(build);
dataSource = build;
}
return dataSource;
}
private static void initPopulate(EmbeddedDatabase embeddedDatabase) {
try {
Connection connection = embeddedDatabase.getConnection();
PreparedStatement prepareStatement;
prepareStatement = connection.prepareStatement("INSERT INTO Settings VALUES (?,?,?)");
prepareStatement.setInt(1, 1);
prepareStatement.setString(2, "testKey");
prepareStatement.setString(3, "testVal");
prepareStatement.executeUpdate();
connection.close();
} catch (SQLException e) {
LOG.error("Error ", e);
}
}
}
schema.sql文件:
CREATE TABLE Settings(
id INT PRIMARY KEY,
testKey VARCHAR(100),
testValue VARCHAR(100)
);
現在,你可以在你的Spring bean使用@Value象下面這樣:
@Value("${testKey}")
private String value;
完整的源代碼可以在這裏找到:https://github.com/szaqal/KitchenSink/tree/master/Java/Spring/propertiesload
待辦事項你不知道如何從彈出的數據庫中讀取值,或者只是關於你的屬性nt閱讀? –