zoukankan      html  css  js  c++  java
  • @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
  • 相关阅读:
    C++入门经典-例8.5-多重继承
    C++入门经典-例8.3-子类显示调用父类构造函数
    C++入门经典-例8.2-构造函数的访问顺序
    C++入门经典-类成员的可访问性,继承后的可访问性
    C++入门经典-例8.1-类的继承
    C++入门经典-例7.10-运算符的重载,重载加号运算符
    C++入门经典-例7.9-对象数组,批量化生产
    C++入门经典-例7.8-const对象,标准尺寸
    C++入门经典-例7.7-对象与复制,菌类的繁殖
    C++入门经典-例7.6-this指针,同一个类的不同对象数据
  • 原文地址:https://www.cnblogs.com/kelelipeng/p/11341274.html
Copyright © 2011-2022 走看看