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 >
        <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,更改下面的配置文件默认编码格式,如下图

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

  • 创建完配置文件,添加nickName值:
nickName=小张三

19.5 还可以通过Environment获取

// 通过 applicationContext 获取配置文件值
String nickName = applicationContext.getEnvironment().getProperty("nickName");
System.out.println(nickName);

19.6 测试用例

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