spring DM支持Configuration Admin,可以使配置文件的内容注入到程序当中。
包括以下三种方式:
1. 把配置文件内容转换为properties,可以设置配置项默认值
<!-- Configuration Admin entry -->
<osgix:cm-properties id="cmProps" persistent-id="com.xyz.myapp">
<prop key="host">localhost</prop>
</osgix:cm-properties>
<!-- placeholder configurer -->
<ctx:property-placeholder properties-ref="cmProps" />
<bean id="dataSource" ...>
<property name="host" value="${host}"/>
<property name="timeout" value="${timeout}"/>
</bean>
2.配置项自动关联对象属性
public class MessageTank {
private int amount;
public int getAmount() { return this.amount; }
public void setAmount(int amount) { this.amount = amount; }
}
<bean id="managedComponent" class="MessageTank">
<osgix:managed-properties persistent-id="com.xyz.messageservice"/>
</bean>
3.配置文件修改后动态加载
<bean id="zhErrorMsgLoader" class="com.sq.platform.webservices.utils.ZhErrorMsgLoaderUtil">
<osgix:managed-properties persistent-id="error_zh_CN" update-strategy="bean-managed" update-method="updateProperties"/>
</bean>
指定update-method方法,update-strategy为“bean-managed”
public class ZhErrorMsgLoaderUtil {
@Autowired
private ErrorMsgFormatter errorMsgFormatter;
public void updateProperties(Map<String, ?> properties) throws UnsupportedEncodingException {
Map<String, String> zhProperties = new HashMap<>();
for (Map.Entry entry : properties.entrySet()) {
zhProperties.put((String) entry.getKey(),
new String(entry.getValue().toString().getBytes("ISO-8859-1"), "UTF-8"));
}
errorMsgFormatter.setCnMsg(zhProperties);
}
}
在karaf容器中运行时,以persistent-id为配置文件名,后缀为”.cfg”,放入etc目录中即可
参考:http://docs.spring.io/osgi/docs/current/reference/html/compendium.html