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,更改下面的配置文件默認編碼格式,如下圖

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

19.5 還可以通過Environment獲取

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

19.6 測試用例


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM