@PropertySouce注解 读取 properties文件

@PropertySouce注解 读取 properties文件,第1张

概述  [email protected] @PropertySouce是spring3.1开始引入的基于java config的注解。 通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。 2. 例子 比如有一个配置文件conf

 

[email protected]

@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 总结

以上是内存溢出为你收集整理的@PropertySouce注解 读取 properties文件全部内容,希望文章能够帮你解决@PropertySouce注解 读取 properties文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1038533.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-24
下一篇2022-05-24

发表评论

登录后才能评论

评论列表(0条)

    保存