配置中心如何动态更新注解
❶ 怎么动态给java注解参数赋值
动态赋值指的是在配置文件配置好然后在项目中动态读取?如果是这样的话:
1.在xml文件中使用<context:property-placeholder location="”/>
这种方式可以读取location指定位置对应的文件,引用的话使用${key}可以获取对应的数据
和这种写法相同的还有
<bean class=“com.spring….config.PropertyPlaceholderConfigurer”>
<property name=“locations">
<array><value></value></array>
</property>
<bean>
这种是用bean来加载配置文件,看起来更直观
2.通过@Value注解读取配置
这种方法也需要预先在xml文件中设定好配置文件的位置
<bean id=“prop” class=“org.springframework.beans.factory.config.PropertiesFactoryBean”>
<property name=“locations”>
<array>
<value>classpath:.properties</value>
</array>
</property>
</bean>
之后在java代码里面可以用#{prop.key}来获取对应的数据prop是bean的名字,key是配置文件的键。
3.使用@PropertySource
在springboot中,可以不需要xml文件来设置配置文件,在需要使用配置文件的类名字前加上
@PropertySource(“locations")就可以读取指定位置的配置,在代码中使用@Value注解可以获取这些数据
@Value(value = “${key}”)
4.使用@ConfigurationProperties(prefix=“”)
SpringBoot项目有时候会使用application.yml来存储配置信息,一般情况下这些数据的存储格式是
a:
key1:value1
key2:value2
这种嵌套方式,当然可以多层嵌套
在需要使用配置文件的类上面使用@ConfigurationProperties(prefix=“a”)可以获取a标签下一层所有的配置的键值对。