Spring boot 数据库里读取属性到system中,以便@Value(${})从system中获取属性值

之前梳理spring启动,bean实例化的时候 有一个知识点是 beanDefination中的property是在beanFactoryPostProcessor中将property文件中的属性值赋给beanDeifination的,但在代码中使用@Value(${property}),debug时(如下),发现是AutowiredAnnotationBeanPostProcessor将属性注入给了bean的成员变量,这里也就是说,@Value()这种bean的成员变量属性的赋值先是发生在beanFactoryPostProcessor中,最终也会通过beanPostProcessor在环境中读取属性并赋值。可以简单的理解为标有@AutoWired 及 @Value的都有自动注入功能,该功能从环境中读取属性。

Spring boot 数据库里读取属性到system中,以便@Value(${})从system中获取属性值

所有 要想从数据库中读取属性并赋值给标有@Value的变量,则只需将数据库中的key-value属性读取到系统环境中:

@Component
public class ReadProperyFromDB implements BeanFactoryPostProcessor {

	@Override
	@SneakyThrows
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		
		Environment env = beanFactory.getBean(Environment.class);
		String url = env.getProperty("spring.datasource.url");
		String username = env.getProperty("spring.datasource.data-username");
		String password = env.getProperty("spring.datasource.data-password");
		
		@Cleanup
		Connection con = DriverManager.getConnection(url, username, password);
		
		@Cleanup
		Statement sta = con.createStatement();
		
		@Cleanup
		ResultSet rs = sta.executeQuery("select pro_key, pro_val from demo where 1=1");
		
		while(rs.next()) {
			System.setProperty(rs.getString(1), rs.getString(2));
		}
		
	}	
}

详见 RADME.md , 如果你喜欢,给颗小星星吧