Чтение списка из файла .properties с использованием Spring свойств владельца места
Я хочу заполнить свойство списка bean, используя Spring владелец места размещения свойств.
Контекстный файл
<bean name="XXX" class="XX.YY.Z">
<property name="urlList">
<value>${prop.list}</value>
</property>
</bean>
Файл свойств
prop.list.one=foo
prop.list.two=bar
Любая помощь будет высоко оценена
Ответы
Ответ 1
Используйте util: свойства для загрузки ваших свойств. Вы можете использовать PropertyPlaceholderConfigurer для указания пути к вашему файлу:
<bean name="XXX" class="XX.YY.Z">
<property name="urlList">
<util:properties location="${path.to.properties.file}"/>
</property>
</bean>
Обновление Я неправильно понял вопрос; вы хотите только вернуть свойства, где ключ начинается с определенной строки. Самый простой способ добиться этого - сделать это в методе setter вашего bean. Вам нужно передать строку в свой bean как отдельное свойство. Расширение указанного объявления:
<bean name="XXX" class="XX.YY.Z" init-method="init">
<property name="propertiesHolder">
<!-- not sure if location has to be customizable here; set it directly if needed -->
<util:properties location="${path.to.properties.file}"/>
</property>
<property name="propertyFilter" value="${property.filter}" />
</bean>
В XX.YY.Z
bean:
private String propertyFilter;
private Properties propertiesHolder;
private List<String> urlList;
// add setter methods for propertyFilter / propertiesHolder
// initialization callback
public void init() {
urlList = new ArrayList<String>();
for (Enumeration en = this.propertiesHolder.keys(); en.hasMoreElements(); ) {
String key = (String) en.nextElement();
if (key.startsWith(this.propertyFilter + ".") { // or whatever condition you want to check
this.urlList.add(this.propertiesHolder.getProperty(key));
}
} // for
}
Если вам нужно сделать это во многих разных местах, вы можете перенести вышеуказанные функции в FactoryBean.
Ответ 2
Более простое решение:
class Z {
private List<String> urlList;
// add setters and getters
}
ваше определение bean
<bean name="XXX" class="XX.YY.Z">
<property name="urlList" value="#{'${prop.list}'.split(',')}"/>
</bean>
Затем в файле свойств:
prop.list=a,b,c,d
Ответ 3
<bean id="cpaContextSource" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="urls">
<bean class="org.springframework.util.CollectionUtils" factory-method="arrayToList">
<constructor-arg type="java.lang.Object">
<bean class="org.springframework.util.StringUtils" factory-method="tokenizeToStringArray">
<constructor-arg type="java.lang.String" value="${myList}"/>
<constructor-arg type="java.lang.String" value=" "/>
</bean>
</constructor-arg>
</bean>
</property>
где:
myList=http://aaa http://bbb http://ccc
Ответ 4
Единственный способ, который я вижу здесь, - реализовать интерфейс MessageSourceAware ', чтобы получить сообщениеResource, а затем вручную заполнить свой список.
class MyMessageSourceAwareClass implemets MessageSourceAware{
public static MessageSource messageSource = null;
public void setMessageSource(MessageSource _messageSource) {
messageSource = _messageSource;
}
public static String getMessage( String code){
return messageSource.getMessage(code, null, null );
}
}
--- Файл свойств ---
prop.list=foo;bar;one more
Заполните свой список следующим образом
String strlist = MyMessageSourceAwareClass.getMessage ( "prop.list" );
if ( StringUtilities.isNotEmptyString ( strlist ) ){
String[] arrStr = strList.split(";");
myBean.setList ( Arrays.asList ( arrStr ) );
}
Ответ 5
Просто добавьте следующее определение Bean
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:myprops.properties</value>
</list>
</property>
</bean>
Чтобы использовать его так, обратите внимание, что порт определен в myprops.properties
<bean id="mybean" class="com.mycompany.Class" init-method="start">
<property name="portNumber" value="${port}"/>
</bean>
Ответ 6
Существует несколько способов: один из них ниже.
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);