[英]How to fill HashMap from java property file with Spring @Value
[英]java spring - override property value received from property file
我有一個場景,我從屬性文件中獲取編碼的密碼值。 我有自己的解密實現,所以想從我的 java 類解密密碼,然后想進一步使用解密的值,在那里引用。
例如<bean id="myDataSource" class="org.apache.common.dbcp.BasicDataSource" ... // more attributed set from properties like user, hostname etc. p:password="${myPropertey.password}" >
上面的代碼我需要實現如下所示的內容,特定於密碼屬性,因為其余屬性很好,但密碼需要在使用前解密。
(下面的實現是錯誤的,但我剛剛提到要給出更多更清晰的想法)
<bean id="myDataSource" class="org.apache.common.dbcp.BasicDataSource" ... // more properties p:password="myDecryptBean.decryptMyPassword(${myPropertey.password})" >
基本上,在用於建立數據庫連接之前,我需要解密從屬性文件中獲取的密碼。
感謝您的時間和任何幫助!
您需要創建一個解密密碼的自定義數據源對象
<bean id="myDataSource" class="foo.bar.PasswordDecryptingDataSource"
... // more properties
p:encryptedPassword="${myPropertey.password}"
>
像這樣實現foo.bar.PasswordDecryptingDataSource
:
public class PasswordDecryptingDataSource extends org.apache.common.dbcp.BasicDataSource {
private myDecryptBean; // inject your decryption bean somehow...
public void setEncryptedPassword(String password) {
super.setPassword(myDecryptBean.decryptMyPassword(password))
}
}
由於您使用的是Spring,我強烈建議您查看PropertyResourceConfigurer
類。 請參閱官方文檔 。
特別要看一下convertProperty(String propertyName, String propertyValue)
方法,並考慮創建一個覆蓋它的類。 然后,您將能夠將自定義解密邏輯添加到overriden方法,該方法將在每次Spring訪問該屬性時運行。
直接來自文檔:
允許從屬性資源(即屬性文件)配置各個bean屬性值。 對自定義配置文件有用...覆蓋在應用程序上下文中配置的bean屬性。
布萊恩,塞繆爾
非常感謝您的快速幫助,這兩種方法都為我的情況提供了解決方案。
我已經實現了擴展PropertyPlaceholderConfigurer,考慮到將來我是否可以獲得更多的屬性,並且不希望將解密邏輯限制到DataSource。
只是我的2美分代碼片段,我已經實現,這可以幫助可能會發現類似情況的人。
<bean class="com.foo.spring.util.PropertyUtil"> <property name="location"> <value>file:${foo.config.location}</value> </property> </bean>
以下是上課
`public class PropertyUtil extends PropertyPlaceholderConfigurer {
@Override
public String convertProperty(String propertyName, String propertyValue){
return super.convertProperty(propertyName, decrypt(propertyValue));
}
private String decrypt(String){
// logical implementation
}
`
我覺得這個線程在這個 PropertyConvertValue 上對我很有幫助。 討論來源
供快速參考:這是我正在使用的解決方法,如果有人覺得它有幫助:
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
final StringValueResolver valueResolver) {
super.doProcessProperties(beanFactoryToProcess,
new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return convertPropertyValue(valueResolver.resolveStringValue(strVal));
}
}
);
}
@Override
protected String convertPropertyValue(String originalValue) {
String value = decrypt(originalValue);
return value;
}
private String decrypt(String value){
//... write decryption logic here
}
類 CustomClass 擴展了 PropertySourcesPlaceholderConfigurer
並覆蓋 doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess, final StringValueResolver valueResolver)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.