spring 如何从属性文件中读取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9259819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read values from properties file?
提问by user1016403
I am using spring. I need to read values from properties file. This is internal properties file not the external properties file. Properties file can be as below.
我正在使用弹簧。我需要从属性文件中读取值。这是内部属性文件而不是外部属性文件。属性文件可以如下。
some.properties ---file name. values are below.
abc = abc
def = dsd
ghi = weds
jil = sdd
I need to read those values from the properties file not in traditional way. How to achieve it? Is there any latest approach with spring 3.0?
我需要不以传统方式从属性文件中读取这些值。如何实现?spring 3.0 有没有最新的方法?
回答by mrembisz
Configure PropertyPlaceholder in your context:
在您的上下文中配置 PropertyPlaceholder:
<context:property-placeholder location="classpath*:my.properties"/>
Then you refer to the properties in your beans:
然后你在你的 bean 中引用属性:
@Component
class MyClass {
@Value("${my.property.name}")
private String[] myValues;
}
EDIT: updated the code to parse property with mutliple comma-separated values:
编辑:更新代码以解析具有多个逗号分隔值的属性:
my.property.name=aaa,bbb,ccc
If that doesnt work, you can define a bean with properties, inject and process it manually:
如果这不起作用,您可以定义一个带有属性的 bean,手动注入和处理它:
<bean id="myProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:my.properties</value>
</list>
</property>
</bean>
and the bean:
和豆子:
@Component
class MyClass {
@Resource(name="myProperties")
private Properties myProperties;
@PostConstruct
public void init() {
// do whatever you need with properties
}
}
回答by user1016403
There are various ways to achieve the same. Below are some commonly used ways in spring-
有多种方法可以实现相同的目标。下面是spring中一些常用的方法——
- Using PropertyPlaceholderConfigurer
- Using PropertySource
- Using ResourceBundleMessageSource
Using PropertiesFactoryBean
and many more........................
- 使用 PropertyPlaceholderConfigurer
- 使用属性源
- 使用 ResourceBundleMessageSource
使用 PropertiesFactoryBean
还有很多........................
Assuming ds.typeis key in your property file.
假设ds.type是您的属性文件中的关键。
Using PropertyPlaceholderConfigurer
使用 PropertyPlaceholderConfigurer
Register PropertyPlaceholderConfigurerbean-
注册PropertyPlaceholderConfigurerbean-
<context:property-placeholder location="classpath:path/filename.properties"/>
or
或者
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:path/filename.properties" ></property>
</bean>
or
或者
@Configuration
public class SampleConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
//set locations as well.
}
}
After registering PropertySourcesPlaceholderConfigurer, you can access the value-
注册后PropertySourcesPlaceholderConfigurer,您可以访问该值-
@Value("${ds.type}")private String attr;
Using PropertySource
使用 PropertySource
In the latest spring version you don't need to register PropertyPlaceHolderConfigurerwith @PropertySource, I found a good linkto understand version compatibility-
在最新版本的春天,你不需要注册PropertyPlaceHolderConfigurer使用@PropertySource,我发现了一个很好的链接,了解版本兼容性-
@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
@Autowired Environment environment;
public void execute() {
String attr = this.environment.getProperty("ds.type");
}
}
Using ResourceBundleMessageSource
使用 ResourceBundleMessageSource
Register Bean-
注册 Bean-
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
Access Value-
访问价值-
((ApplicationContext)context).getMessage("ds.type", null, null);
or
或者
@Component
public class BeanTester {
@Autowired MessageSource messageSource;
public void execute() {
String attr = this.messageSource.getMessage("ds.type", null, null);
}
}
Using PropertiesFactoryBean
使用 PropertiesFactoryBean
Register Bean-
注册 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 Properties instance into your class-
将属性实例连接到您的类中-
@Component
public class BeanTester {
@Autowired Properties properties;
public void execute() {
String attr = properties.getProperty("ds.type");
}
}
回答by mokshino
In configuration class
在配置类
@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;
}
}
回答by Michael Técourt
Here is an additional answer that was also great help for me to understand how it worked : http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html
这是一个额外的答案,对我理解它是如何工作的也有很大帮助:http: //www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html
any BeanFactoryPostProcessor beans have to be declared with a static, modifier
任何 BeanFactoryPostProcessor beans 都必须使用static, 修饰符声明
@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();
}
}
回答by John
If you need to manually read a properties file without using @Value.
如果您需要在不使用 @Value 的情况下手动读取属性文件。
Thanks for the well written page by Lokesh Gupta : Blog
感谢 Lokesh Gupta 写得很好的页面:博客
package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;
public class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());
public static Properties fetchProperties(){
Properties properties = new Properties();
try {
File file = ResourceUtils.getFile("classpath:application.properties");
InputStream in = new FileInputStream(file);
properties.load(in);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return properties;
}
}
回答by instanceOfObject
You need to put a PropertyPlaceholderConfigurer bean in your application context and set its location property.
您需要在应用程序上下文中放置一个 PropertyPlaceholderConfigurer bean 并设置其位置属性。
See details here : http://www.zparacha.com/how-to-read-properties-file-in-spring/
在此处查看详细信息:http: //www.zparacha.com/how-to-read-properties-file-in-spring/
You might have to modify your property file a bit for this thing to work.
您可能需要稍微修改您的属性文件才能使此功能正常工作。
Hope it helps.
希望能帮助到你。
回答by Miluna
Another way is using a ResourceBundle. Basically you get the bundle using its name without the '.properties'
另一种方法是使用ResourceBundle。基本上你使用它的名字来获得包,而没有“.properties”
private static final ResourceBundle resource = ResourceBundle.getBundle("config");
And you recover any value using this:
您可以使用以下方法恢复任何值:
private final String prop = resource.getString("propName");
回答by Sida Zhou
I wanted an utility class which is not managed by spring, so no spring annotations like @Component, @Configurationetc. But I wanted the class to read from application.properties
我想这不是由Spring管理的实用工具类,所以没有春天注解喜欢@Component,@Configuration等等。但我希望从类阅读application.properties
I managed to get it working by getting the class to be aware of the Spring Context, hence is aware of Environment, and hence environment.getProperty()works as expected.
我设法通过让类知道 Spring Context 来使其工作,因此知道Environment,因此environment.getProperty()按预期工作。
To be explicit, I have:
明确地说,我有:
application.properties
应用程序属性
mypath=somestring
Utils.java
实用程序
import org.springframework.core.env.Environment;
// No spring annotations here
public class Utils {
public String execute(String cmd) {
// Making the class Spring context aware
ApplicationContextProvider appContext = new ApplicationContextProvider();
Environment env = appContext.getApplicationContext().getEnvironment();
// env.getProperty() works!!!
System.out.println(env.getProperty("mypath"))
}
}
ApplicationContextProvider.java(see Spring get current ApplicationContext)
ApplicationContextProvider.java(参见Spring 获取当前 ApplicationContext)
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
public ApplicationContext getApplicationContext() {
return CONTEXT;
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
}
回答by theyCallMeJun
I'll recommend reading this link https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.htmlfrom SpringBoot docs about injecting external configs. They didn't only talk about retrieving from a properties file but also YAML and even JSON files. I found it helpful. I hope you do too.
我建议阅读SpringBoot 文档中有关注入外部配置的链接https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html。他们不仅谈到了从属性文件中检索,还谈到了 YAML 甚至 JSON 文件。我发现它很有帮助。我希望你也这样做。
回答by Sangram Badi
[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>


