spring中引入property文件的三种方式

目前我了解的共有三种方式来引入property文件,必须要引入文件以后,才能使用${}的方式来获取其中的值

方式一:

在xml配置文件中加入

<bean id="pro" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

            <property name="locations">

                    <list>

                            <value>classpath:user.property</value>

                    </list>

            </property>

</bean>

多个资源的时候,在list标签下面继续增加<value>即可

 

方式二:

在xml配置文件中加入

 <context:property-placeholder location="classpath:user.property,classpath:user2.property"/>,多个资源可以用逗号隔开写在一起

 

方式三:

在配置类上进行添加注解

@PropertySource("user.property")

或者

@PropertySources({@PropertySource("user.property"),@PropertySource("user1.property")})

 

然后结合@value取值即可

如下

//@PropertySource("user.property")

@PropertySources({@PropertySource("user.property"),@PropertySource("user1.property")})

@Configuration

public class PropertiesCOnfig {

@Bean

public TestConfig getTestConfig(@Value("${user.name}") String name,@Value("${user.age}") String age) {

TestConfig t=new TestConfig();

t.setName(name);

t.setAge(age);

return t;

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot应用程序,可以使用 `application.yml` 或 `application.properties` 文件来配置应用程序属性。如果您正在使用 `application.yml` 文件,您可以使用 `@PropertySource` 注释和 `@ConfigurationProperties` 注释来从 `application.yml` 文件加载属性。 以下是将 `application.yml` 文件的属性加载到 Spring Boot 应用程序的示例: 1. 在 `application.yml` 文件设置您的属性: ``` myproperty: name: "my name" age: 25 ``` 2. 创建一个类来保存您的属性: ``` @Component @ConfigurationProperties(prefix = "myproperty") public class MyProperty { private String name; private int age; // getters and setters } ``` 3. 在您的应用程序使用 MyProperty 类: ``` @RestController public class MyController { @Autowired private MyProperty myProperty; @GetMapping("/myproperty") public String getMyProperty() { return "Name: " + myProperty.getName() + ", Age: " + myProperty.getAge(); } } ``` 在上面的示例,`@ConfigurationProperties` 注释设置了属性的前缀,因此 Spring Boot 将自动从 `application.yml` 文件加载属性。在 `MyController` ,我们将 `MyProperty` 类注入并使用其的属性。 注意事项:如果您使用的是 `application.properties` 文件,则需要将 `@PropertySource` 注释添加到您的类,并指定属性文件的位置。例如: ``` @Component @PropertySource("classpath:myproperties.properties") @ConfigurationProperties(prefix = "myproperty") public class MyProperty { // ... } ``` 其,`classpath:myproperties.properties` 是 `application.properties` 文件的位置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值