从数据库加载spring boot app属性

时间:2017-09-25 14:07:52

标签: spring-boot properties

我需要你就这个问题向我提出建议,在Spring启动应用程序中我从数据库加载了一些属性,如(cron period,email data),我需要在应用程序上下文中导出这些属性以便弹出构建相应的加载数据的bean。我怎么能这样做?

3 个答案:

答案 0 :(得分:4)

对于那些在应用程序启动之前需要从数据库加载属性的人,并使@Value可以在项目的任何位置访问这些道具,只需添加此处理器。

public class ReadDbPropertiesPostProcessor implements EnvironmentPostProcessor {
/**
 * Name of the custom property source added by this post processor class
 */
private static final String PROPERTY_SOURCE_NAME = "databaseProperties";

private String[] KEYS = {
        "excel.threads",
        "cronDelay",
        "cronDelayEmail",
        "spring.mail.username",
        "spring.mail.password",
        "spring.mail.host",
        "spring.mail.port",
        "spring.mail.properties.mail.transport.protocol",
        "spring.mail.properties.mail.smtp.auth",
        "spring.mail.properties.mail.smtp.starttls.enabled",
        "spring.mail.properties.mail.debug",
        "spring.mail.properties.mail.smtp.starttls.required",
        "spring.mail.properties.mail.socketFactory.port",
        "spring.mail.properties.mail.socketFactory.class",
        "spring.mail.properties.mail.socketFactory.fallback",
        "white.executor.threads",
        "white.search.threads",
        "lot.sync.threads",
        "lot.async.threads",
        "lot.soap.threads",
        "excel.async.threads",
        "kpi.threads",
        "upload.threads"
};

/**
 * Adds Spring Environment custom logic. This custom logic fetch properties from database and setting highest precedence
 */
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

    Map<String, Object> propertySource = new HashMap<>();

    try {

        // Build manually datasource to ServiceConfig
        DataSource ds = DataSourceBuilder
                .create()
                .username(environment.getProperty("spring.datasource.username"))
                .password(environment.getProperty("spring.mail.password"))
                .url(environment.getProperty("spring.datasource.url"))
                .driverClassName("com.mysql.jdbc.Driver")
                .build();

        // Fetch all properties

        Connection connection = ds.getConnection();

        JTrace.genLog(LogSeverity.informational, "cargando configuracion de la base de datos");

        PreparedStatement preparedStatement = connection.prepareStatement("SELECT value FROM config WHERE id = ?");

        for (int i = 0; i < KEYS.length; i++) {

            String key = KEYS[i];

            preparedStatement.setString(1, key);

            ResultSet rs = preparedStatement.executeQuery();

            // Populate all properties into the property source
            while (rs.next()) {
                propertySource.put(key, rs.getString("value"));
            }

            rs.close();
            preparedStatement.clearParameters();

        }

        preparedStatement.close();
        connection.close();

        // Create a custom property source with the highest precedence and add it to Spring Environment
        environment.getPropertySources().addFirst(new MapPropertySource(PROPERTY_SOURCE_NAME, propertySource));

    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

application.properties 中必须存在数据源数据才能连接到数据库。

然后在文件夹 META-INF 中创建一个名为 spring.factories 的文件,其中包含以下行:

org.springframework.boot.env.EnvironmentPostProcessor=test.config.ReadDbPropertiesPostProcessor

就是这样,可以在任何地方访问已检索到的属性。

答案 1 :(得分:1)

我认为使用BeanPostProcessor和Binder是个好主意,这样您就无需列出要阅读的所有属性。 以下代码引用ConfigurationPropertiesBindingPostProcessor。

public class PropertiesInsideDatabaseInitializer implements BeanPostProcessor, InitializingBean, ApplicationContextAware {

    private JdbcTemplate jdbcTemplate;
    private ApplicationContext applicationContext;
    private BeanDefinitionRegistry registry;
    private Map<String, Object> systemConfigMap = new HashMap<>();

    private final String propertySourceName = "propertiesInsideDatabase";

    public PropertiesInsideDatabaseInitializer(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        bind(ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName));
        return bean;
    }

    private void bind(ConfigurationPropertiesBean propertiesBean) {
        if (propertiesBean == null || hasBoundValueObject(propertiesBean.getName())) {
            return;
        }
        Assert.state(propertiesBean.getBindMethod() == ConfigurationPropertiesBean.BindMethod.JAVA_BEAN, "Cannot bind @ConfigurationProperties for bean '"
                + propertiesBean.getName() + "'. Ensure that @ConstructorBinding has not been applied to regular bean");
        try {
            Bindable<?> target = propertiesBean.asBindTarget();
            ConfigurationProperties annotation = propertiesBean.getAnnotation();
            BindHandler bindHandler = new IgnoreTopLevelConverterNotFoundBindHandler();
            MutablePropertySources mutablePropertySources = new MutablePropertySources();
            mutablePropertySources.addLast(new MapPropertySource(propertySourceName, systemConfigMap));
            Binder binder = new Binder(ConfigurationPropertySources.from(mutablePropertySources), new PropertySourcesPlaceholdersResolver(mutablePropertySources),
                    ApplicationConversionService.getSharedInstance(), getPropertyEditorInitializer(), null);
            binder.bind(annotation.prefix(), target, bindHandler);
        }
        catch (Exception ex) {
            throw new BeanCreationException("", ex);
        }
    }

    private Consumer<PropertyEditorRegistry> getPropertyEditorInitializer() {
        if (this.applicationContext instanceof ConfigurableApplicationContext) {
            return ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory()::copyRegisteredEditorsTo;
        }
        return null;
    }

    private boolean hasBoundValueObject(String beanName) {
        return this.registry.containsBeanDefinition(beanName) && this.registry
                .getBeanDefinition(beanName).getClass().getName().contains("ConfigurationPropertiesValueObjectBeanDefinition");
    }

    @Override
    public void afterPropertiesSet() {
        String sql = "SELECT key, value from system_config";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : maps) {
            String key = String.valueOf(map.get("key"));
            Object value = map.get("value");
            systemConfigMap.put(key, value);
        }
        this.registry = (BeanDefinitionRegistry) this.applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

还可以在环境中修改PropertySources。实现BeanPostProcessor接口可以在创建Bean之前对其进行初始化

public class PropertiesInsideDatabaseInitializer implements BeanPostProcessor, InitializingBean, EnvironmentAware {

    private JdbcTemplate jdbcTemplate;
    private ConfigurableEnvironment environment;

    private final String propertySourceName = "propertiesInsideDatabase";


    public PropertiesInsideDatabaseInitializer(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void afterPropertiesSet() {
        if(environment != null){
            Map<String, Object> systemConfigMap = new HashMap<>();
            String sql = "SELECT key, value from system_config";
            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> map : maps) {
                String key = String.valueOf(map.get("key"));
                Object value = map.get("value");
                systemConfigMap.put(key, value);
            }
            environment.getPropertySources().addFirst(new MapPropertySource(propertySourceName, systemConfigMap));
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        if(environment instanceof ConfigurableEnvironment){
            this.environment = (ConfigurableEnvironment) environment;
        }
    }
}

答案 2 :(得分:0)

您可以根据需要手动使用数据库值配置Bean(通过这种方式,您可以利用Spring CDI和启动数据库配置)。

以设置会话超时为例:

@SpringBootApplication
public class MySpringBootApplication extends SpringBootServletInitializer {           
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }

    @Bean
    public HttpSessionListener httpSessionListener(){
        return new MyHttpSessionListener();
    }
}

然后是用于配置bean的bean定义:

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyHttpSessionListener implements HttpSessionListener {   
    @Autowired
    private MyRepository myRepository;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        se.getSession().setMaxInactiveInterval(this.myRepository.getSessionTimeoutSeconds()); 
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // Noop
    }

}

注意:您可以将数据库调用移至@PostConstruct方法,以避免在每次会话时都进行调用。