@PropertySouce注解 讀取 properties文件


https://www.cnblogs.com/whx7762/p/7885735.html

 

1.@ProtertySource

@PropertySouce是spring3.1開始引入的基於java config的注解。

通過@PropertySource注解將properties配置文件中的值存儲到Spring的 Environment中,Environment接口提供方法去讀取配置文件中的值,參數是properties文件中定義的key值。

2. 例子

比如有一個配置文件config.properties

jdbc.driver = oracle.jdbc.driver.OracleDriver

jdbc.url = jdbc\:oracle\:thin\:@(DESCRIPTION\=(ADDRESS\=(PROTOCOL\=TCP)(HOST\=10.221.129.208)(PORT\=1523))(CONNECT_DATA\=(SERVICE_NAME\=otatransuser)))

jdbc.username= sassy

jdbc.password = password

2.1  用法1- @PropertySource和@Value

創建java配置類

復制代碼
@Configuration
@PropertySource("classpath:jdbc.properties")
public class PropertiesWithJavaConfig {

@Value(${jdbc.driver}) private String driver;
@Value(${jdbc.url}) private String url;
@Value(${jdbc.username}) private String username;
@Value(${jdbc.password}) private String password;
//要想使用@Value 用${}占位符注入屬性,這個bean是必須的,這個就是占位bean,另一種方式是不用value直接用Envirment變量直接getProperty('key')   @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
復制代碼

2.2 用法2-通過Environment設置

復制代碼
@Configuration
@PropertySource("classpath:jdbc.properties")
public class PropertiesWithJavaConfig {

   @Autowired
    private Environment env;

}
復制代碼

接着就可以用env.getProperty("jdbc.driver")得到相應的屬性值

3.等同於在xml中配置properties文件

復制代碼
?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-4.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

      <context:property-placeholder location="classpath:jdbc.properties" />

</beans>
復制代碼

 

在Spring 4中,Spring提供了一個新的注解——@PropertySources,從名字就可以猜測到它是為多配置文件而准備的。

@PropertySources({

@PropertySource("classpath:config.properties"),

@PropertySource("classpath:db.properties")

})

public class AppConfig {

    //something

}

 

 
分類:  Spring


免責聲明!

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



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