Spring读取properties文件

假设此时有properties文件:mytest.properties

testKey=testValue

1 利用PropertyPlaceholderConfigurer

1.1 注解

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:mytest.properties" />
</bean>

如果有多个文件的话:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
           <list>
               <value>mytest1.properties</value>
               <value>mytest2.properties</value>
           </list>
       </property>
</bean>

此时可以使用@Value直接使用:

@Value("${testKey}")
String configVal;

1.2 维护到容器中

或者继承PropertyPlaceholderConfigurer,将文件内容解析后放到一个容器中:

public class TestConfigurer extends PropertyPlaceholderConfigurer {

    private Map<String,Object> testPropMap;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        if(null == testPropMap){
            testPropMap= new HashMap<>();
        }
        for (Object key : props.keySet()){
            String keyStr = key.toString();
            Object value = props.get(key);
            testPropMap.put(keyStr,value);
        }
    }
    public List<String> getCtxProp(String name) {
        return encryptPropMap.get(name);
    }
}

<bean id="testConfigurer " class="com.test.TestConfigurer">
    <property name="location">
        <value>classpath:conf/mytest.properties</value>
    </property>
</bean>

此时就可以通过注入testConfigurer来获取了。

2 PropertiesFactoryBean

PropertiesFactoryBean使用上和PropertyPlaceholderConfigurer类似,仅仅是注解使用身上有些差异

<bean id="testConfig" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:mytest.properties" />
</bean>

然后用注解:

@Value("#{$testConfig['testKey']}")
int configVal;

3 Properties与InputStream

此种方式可以动态的读取Properties文件,比如定义一个读取文件的类:

public class TestConfigurer {
	public static Properties getConfig(String configPath){
        InputStream inputStream = TestConfigurer .class.getResourceAsStream(configPath);
        if (inputStream == null) {
            return null;
        }
        try {
            Properties properties = new Properties();
            properties.load(inputStream);
            return properties;
        } catch (Exception e) {
            throw new RuntimeException("load config error", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException ioe) {
                logger.error("close stream error", ioe);
            }
        }
    }
}

只要传入路径就能获取到Properties实例,也就获得了文件内容.
关于getResourceAsStream是用法,可以参考一下:Java中getResourceAsStream的用法这篇博文

4 PropertiesLoaderUtils与Resource

此种方式和类似,可以动态读取文件:

Resource resource = new ClassPathResource("/myTest.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

路径

关于文件路径,如果路径以‘/’开头,则表示classpath目录下。

参考资料:
Spring获取properties文件中的属性

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring可以通过`PropertyPlaceholderConfigurer`来读取properties文件。 1. 在Spring配置文件中添加`PropertyPlaceholderConfigurer`的bean: ```xml <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean> ``` 2. 在properties文件中定义属性: ```properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=123456 ``` 3. 在Spring配置文件中使用属性: ```xml <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> ``` 这样就可以通过Spring读取properties文件中的属性了。 ### 回答2: Spring 是一个广泛使用的框架,受欢迎的一个原因是其简化了很多任务。其中之一就是读取 properties 文件。在 Spring 中,我们不必自己编写代码从文件读取属性。我们可以利用 Spring 的功能来自动读取属性,使得我们可以更加专注于应用程序的业务逻辑,并且遵循 Spring 管理原则。 Spring 提供了多种读取 properties 文件的方式。下面是其中的几种常见方式: 1. 使用 @Value 注解 @Value 注解本质上将属性文件的值注入到我们的 Java 类中。例如,我们可以在 Spring 的配置文件中定义以下属性值: application.properties ```properties app.name=My Application app.version=1.0 ``` 然后在我们的 Java 类中,在需要的属性前面加上 @Value 注解即可。 ```java @Component public class MyComponent { @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; // ... } ``` 2. 使用 PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer 是一个特殊的 bean,它读取属性文件并将属性值注入到其他 bean 中。配置方式如下: ```xml <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/application.properties</value> </list> </property> </bean> ``` 然后,在 Java 类中可以使用 @Value 注解获取属性值。 3. 配置文件的统一管理 Spring 还提供了一个功能来统一管理配置文件。每个应用程序可能需要多个配置文件,所以 Spring 提供了一种方法来将这些配置文件合并为一个层次结构。这种方式称为 “Environment Abstraction”,它允许应用程序使用一组由多个配置文件组成的 “属性源”。 ```java @Configuration @PropertySource("classpath:/application.properties") public class AppConfig { @Autowired Environment env; @Bean public MyComponent myComponent() { MyComponent component = new MyComponent(); component.setAppName(env.getProperty("app.name")); component.setAppVersion(env.getProperty("app.version")); return component; } } ``` 以上是 Spring 读取 properties 文件的常见方式。开发者可以根据自己的需求选择不同的方式。无论选择哪种方式,Spring 已经为我们创建了属性文件读取的底层机制和简化方式,使得我们更加便利地开发。 ### 回答3: Spring读取properties文件是很常见的操作,通常我们会在配置文件中声明需要读取文件路径,并通过注入的方式将文件中的内容读取Spring的环境中。以下是更详细的步骤: 1. 确定properties文件的存储位置和名称。可以将其放置在classpath下或者指定文件路径。这里假设放在classpath下,文件名为config.properties。 2. 在Spring的配置文件中使用以下语句引用这个properties文件: ``` <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean> ``` 这里使用了Spring提供的“PropertyPlaceholderConfigurer”类。这个类允许我们将properties文件的内容注入到Spring的环境中。 3. 在需要读取properties文件的类中注入这个“PropertyPlaceholderConfigurer”对象,并使用以下语句读取其中的值: ``` @Value("${key}") private String value; ``` 其中,key是properties文件中的键名,value则为其对应的值。 另外,还可以通过“ResourceBundleMessageSource”类直接读取properties文件中的文本资源,例如: ``` ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("config"); String message = messageSource.getMessage("key", null, Locale.getDefault()); ``` 这里使用了Spring提供的“ResourceBundleMessageSource”类,将properties文件中的文本资源转换为字符串类型的message。 总之,读取properties文件Spring开发中一个比较基础的操作,熟练掌握此技能可以提高代码开发效率,并且为系统开发提供清晰的配置方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yue_hu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值