spring读取多个properties文件

项目中可能出现多个properties文件,比如数据库的jdbc.properties,redis的redis.properties等

在spring的配置文件中可以有两种方法读取properties文件

===============================分割线===================================

一,

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
  <value>classpath:redis/redis-config.properties</value>

  <value>classpath:database/jdbc.properties</value>

</list>
</property>
</bean>

========================分割线===================================

二,

 <context:property-placeholder location="classpath:database/jdbc.properties" ignore-unresolvable="true"/>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 中,可以通过 `@Value` 注解来读取配置文件中的属性。但是如果属性很多,一个个用 `@Value` 注解来读取会很麻烦。因此,Spring 提供了一个更便捷的方式来读取属性,那就是使用 `@ConfigurationProperties` 注解。 `@ConfigurationProperties` 注解可以将配置文件中的属性映射到一个 Java 类中,然后通过 `@Autowired` 注入这个类来使用其中的属性。具体步骤如下: 1. 定义一个 Java 类,类中的属性名称需要与 application.properties 文件中的属性名称一致,并且需要提供相应的 getter 和 setter 方法。 ```java @ConfigurationProperties(prefix = "example") public class ExampleProperties { private String name; private int age; // getter 和 setter 方法 } ``` 2. 在 application.properties 文件中定义属性。 ``` example.name=张三 example.age=18 ``` 3. 在 Spring 配置类中使用 `@EnableConfigurationProperties` 注解开启属性配置功能,并将上面定义的 `ExampleProperties` 类注入到 Spring 容器中。 ```java @Configuration @EnableConfigurationProperties(ExampleProperties.class) public class AppConfig { @Autowired private ExampleProperties exampleProperties; // 其他配置 } ``` 4. 在需要使用属性的地方注入 `ExampleProperties` 类,并使用其中的属性。 ```java @Service public class ExampleService { @Autowired private ExampleProperties exampleProperties; public void printProperties() { System.out.println("name: " + exampleProperties.getName()); System.out.println("age: " + exampleProperties.getAge()); } } ``` 这样就可以方便地读取配置文件中的属性了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值