Как читать значения из файла свойств?
Я использую spring. Мне нужно прочитать значения из файла свойств. Это внутренний файл свойств, а не файл внешних свойств. Файл свойств может быть следующим.
some.properties ---file name. values are below.
abc = abc
def = dsd
ghi = weds
jil = sdd
Мне нужно прочитать эти значения из файла свойств не традиционным способом. Как его достичь? Есть ли какой-либо последний подход с spring 3.0?
Ответы
Ответ 1
Настроить PropertyPlaceholder в вашем контексте:
<context:property-placeholder location="classpath*:my.properties"/>
Затем вы ссылаетесь на свойства в beans:
@Component
class MyClass {
@Value("${my.property.name}")
private String[] myValues;
}
EDIT: обновлен код для синтаксического анализа с помощью значений, разделенных запятыми:
my.property.name=aaa,bbb,ccc
Если это не работает, вы можете определить bean со свойствами, ввести и обработать его вручную:
<bean id="myProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:my.properties</value>
</list>
</property>
</bean>
и bean:
@Component
class MyClass {
@Resource(name="myProperties")
private Properties myProperties;
@PostConstruct
public void init() {
// do whatever you need with properties
}
}
Ответ 2
В классе конфигурации
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
Ответ 3
Вот еще один ответ, который также помог мне понять, как это работает: http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html
любой BeanFactoryPostProcessor beans должен быть объявлен с помощью статического, модификатора
@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {
@Value("${test.prop}")
private String attr;
@Bean
public SampleService sampleService() {
return new SampleService(attr);
}
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Ответ 4
Существуют различные способы достижения этого. Ниже приведены некоторые распространенные способы использования spring -
Предполагая, что ds.type
является ключом вашего файла свойств.
Использование PropertyPlaceholderConfigurer
Зарегистрировать PropertyPlaceholderConfigurer
bean -
<context:property-placeholder location="classpath:path/filename.properties"/>
или
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:path/filename.properties" ></property>
</bean>
или
@Configuration
public class SampleConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
//set locations as well.
}
}
После регистрации PropertySourcesPlaceholderConfigurer
теперь вы можете получить доступ к значению -
@Value("${ds.type}")private String attr;
Использование PropertySource
В последней версии spring не нужно регистрировать PropertyPlaceholderConfigurer
с помощью @PropertySource
, я нашел хорошую ссылку , чтобы понять совместимость версии -
@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
@Autowired Environment environment;
public void execute(){
String attr = this.environment.getProperty("ds.type");
}
}
Использование ResourceBundleMessageSource
Зарегистрировать bean -
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
Значение доступа -
((ApplicationContext)context).getMessage("ds.type", null, null);
или
@Component
public class BeanTester {
@Autowired MessageSource messageSource;
public void execute(){
String attr = this.messageSource.getMessage("ds.type", null, null);
}
}
Использование PropertiesFactoryBean
Зарегистрировать bean -
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
Экземпляр свойств Wire в ваш класс -
@Component
public class BeanTester {
@Autowired Properties properties;
public void execute(){
String attr = properties.getProperty("ds.type");
}
}
Ответ 5
Вам нужно поместить PropertyPlaceholderConfigurer bean в свой контекст приложения и установить его свойство location.
Подробнее здесь: http://www.zparacha.com/how-to-read-properties-file-in-spring/
Возможно, вам придется немного изменить свой файл свойств, чтобы эта работа работала.
Надеюсь, что это поможет.
Ответ 6
[project structure]: http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
package beans;
import java.util.Properties;
import java.util.Set;
public class PropertiesBeans {
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void getProperty(){
Set keys = properties.keySet();
for (Object key : keys) {
System.out.println(key+" : "+properties.getProperty(key.toString()));
}
}
}
----------------------------
package beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
PropertiesBeans p = (PropertiesBeans)ap.getBean("p");
p.getProperty();
}
}
----------------------------
- driver.properties
Driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test
username = root
password = root
----------------------------
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="p" class="beans.PropertiesBeans">
<property name="properties">
<util:properties location="classpath:resource/driver.properties"/>
</property>
</bean>
</beans>