19、属性赋值-@PropertySource加载外部配置文件

19、属性赋值-@PropertySource加载外部配置文件

  • 加载外部配置文件的注解
19.1 【xml】
  • 在原先的xml 中需要 导入context:property-placeholder 声明,然后使用${nickName}取值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--包扫描 , 只要标注了 @Controller 、@Service、@Repository、@Component的类 都会被扫描-->
    <context:component-scan base-package="com.hw.springannotation"></context:component-scan>
    <!--导入配置文件中的属性值-->
    <context:property-placeholder location="classpath:pension.properties"></context:property-placeholder>
    <bean id="pension" class="com.hw.springannotation.beans.Pension" scope="prototype" init-method="" destroy-method="">
        <property name="name" value="hw"></property>
        <property name="age" value="18"></property>
        <property name="nickName" value="${nickName}"></property>
    </bean>
</beans>
19.2 【注解】@PropertySource
  • 使用@PropertySource来读取外部配置文件中的k/v值 保存到运行的环境变量中,加载完就可以使用${变量名}取出
// 使用@PropertySource来读取外部配置文件中的k/v值 保存到运行的环境变量中,加载完就可以使用${}取出
@PropertySource(value = {"classpath:/pension.properties"})
@Configuration
public class MainConfigOfPropertyValues {
    @Bean
    public Pension pension() {
        return new Pension();
    }

}
19.3 pension类新添加nickName属性
@Value("张三")
private String name;
@Value("#{22-1}")
private Integer age;
@Value("${nickName}")
private String nickName;
19.4 新建pension.properties配置文件
  • 注意,在这里一定要注意项目的编码,本项目都是采用UTF-8编码,配置文件也是(idea默认是GBK,会导致读取的配置文件乱码)
  • 可以在idea设置中搜索File-Encodeings,更改下面的配置文件默认编码格式,如下图

1221855-20181129155612954-714011444.png

  • 创建完配置文件,添加nickName值:
nickName=小张三
19.5 还可以通过Environment获取
// 通过 applicationContext 获取配置文件值
String nickName = applicationContext.getEnvironment().getProperty("nickName");
System.out.println(nickName);
19.6 测试用例

1221855-20181129155947133-1488423449.png

转载于:https://www.cnblogs.com/Grand-Jon/p/10038901.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值