вам нужно создать свои собственные пользовательские реализации имущества загрузчика:
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)
);
Теперь вы можете использовать @value, как показано ниже в вашем весеннем боба:
@Value("${testKey}")
private String value;
Полный исходный код доступен здесь: https://github.com/szaqal/KitchenSink/tree/master/Java/Spring/propertiesload
Do вы не знаете, как читать значения из базы данных с весной в gerneral или это только о свойствах, которые вы nt читать? –