【问题标题】:Load spring boot app properties from database从数据库加载 Spring Boot 应用程序属性
【发布时间】:2017-09-25 14:07:51
【问题描述】:

我需要你就这个问题给我建议,在 Spring Boot 应用程序中,我从数据库中加载了一些属性,例如(cron 周期、电子邮件数据),我需要在应用程序上下文中导出这些属性以便构建相应的带有加载数据的bean。我怎么能这样做?

【问题讨论】:

  • 下面的链接怎么样;stackoverflow.com/questions/40465360/…
  • 我已经尝试过该示例,但它仅适用于第二次重启。现在,我读到了评论“数据库中的那些属性可用于配置 Bean。虽然我更愿意不在 @PostConstruct 中而是在自定义 BeanPostProcessor 中初始化它们,只是在 DataSource 启动后”,你能告诉我如何这样做?
  • 您是想从数据库中获取@Value 属性注入的值,还是只想要一个由数据库中的这些属性组成的bean?
  • 您好,Phani 感谢您的回复,我需要第一个选项,但我已经找到了解决方案,我会立即发布。

标签: spring-boot properties


【解决方案1】:

对于那些需要在应用程序启动之前从数据库加载属性,并在项目中的任何地方通过@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);
    }
}
} // class ReadDbPropertiesPostProcessor end

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

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

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

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

【讨论】:

  • 如果我想从数据库中读取值,比如我的电子邮件服务的用户名,这会起作用吗?
  • 没错,就是从数据库中加载配置数据。
【解决方案2】:

我认为使用 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;
    }
}

修改Environment中的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;
        }
    }
}

【讨论】:

    【解决方案3】:

    您可以根据需要手动使用数据库值配置 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 方法以避免每次会话都调用它。

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2020-09-07
      • 2021-06-05
      • 2019-03-16
      • 2015-01-23
      • 2019-03-18
      • 1970-01-01
      • 2018-03-23
      • 2020-05-26
      相关资源
      最近更新 更多