之前梳理spring启动,bean实例化的时候 有一个知识点是 beanDefination中的property是在beanFactoryPostProcessor中将property文件中的属性值赋给beanDeifination的,但在代码中使用@Value(${property}),debug时(如下),发现是AutowiredAnnotationBeanPostProcessor将属性注入给了bean的成员变量,这里也就是说,@Value()这种bean的成员变量属性的赋值先是发生在beanFactoryPostProcessor中,最终也会通过beanPostProcessor在环境中读取属性并赋值。可以简单的理解为标有@AutoWired 及 @Value的都有自动注入功能,该功能从环境中读取属性。
所有 要想从数据库中读取属性并赋值给标有@Value的变量,则只需将数据库中的key-value属性读取到系统环境中:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28@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 , 如果你喜欢,给颗小星星吧
最后
以上就是舒心毛豆最近收集整理的关于Spring boot 数据库里读取属性到system中,以便@Value(${})从system中获取属性值的全部内容,更多相关Spring内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复