zoukankan      html  css  js  c++  java
  • spring 加载属性(properties)文件

      在开发的过程中,配置文件往往就是那些属性(properties)文件,比如使用properties文件配置数据库文件,又如database-config.properties
      代码清单:database-config.properties

    jdbc.database.driver=com.mysql.cj.jdbc.Driver 
    jdbc.database.url=jdbc:mysql://localhost:3306/springmvc?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true
    jdbc.database.username=root
    jdbc.database.password=123456

      使用属性文件可以有效地减少硬编码,很多时候修改环境只需要修改配置文件就可以了,这样能够有效提高运维人员的操作便利性,所以使用properties文件是十分常见的场景。在Spring中也可以通过注解或者XML的方式进行加载属性文件

    使用注解方式加载属性文件

      Spring提供了注解@PropertySource来加载属性文件,了解它的配置项。
      •name:字符串,配置这次属性配置的名称。
      •value:字符串数组,可以配置多个属性文件。
      •ignoreResourceNotFound:boolean值,默认为false,其含义为如果找不到对应的属性文件是否进行忽略处理,由于默认值为false,所以在默认的情况下找不到对应的配置文件会抛出异常。
      •encoding:编码,默认为""。

      代码清单:在Spring环境中使用属性文件Java配置

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.ImportResource;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
    
    @Configuration
    // @ComponentScan(basePackages = {"com.ssm.chapter10.annotation"})
    @ImportResource({"classpath:ssm/chapter10/spring-dataSource.xml"})
    @PropertySource(value = {"classpath:ssm/chapter10/database-config.properties"})
    public class ApplicationConfig2 {
    }

      代码清单:测试加载属性

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig2.class);
    String url = context.getEnvironment().getProperty("jdbc.database.url");
    System.out.println(url);

      Spring中是没有解析属性占位符的能力,Spring推荐使用一个属性文件解析类进行处理,它就是PropertySources Placeholder-Configurer,使用它就意味着允许Spring解析对应的属性文件,并通过占位符去引用对应的配置。

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.ImportResource;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
    
    @Configuration
    // @ComponentScan(basePackages = {"com.ssm.chapter10.annotation"})
    @ImportResource({"classpath:ssm/chapter10/spring-dataSource.xml"})
    @PropertySource(value = {"classpath:ssm/chapter10/database-config.properties"})
    public class ApplicationConfig2 {
    
        /**
         * 作用是为了让Spring能够解析属性占位符,
         */
        @Bean
        public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
    }

      引用已经定义好的配置,这里可以使用注解@Value和占位符

    import org.apache.commons.dbcp.BasicDataSourceFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    
    import javax.sql.DataSource;
    import java.util.Properties;
    
    @Component
    public class ProfileDataSource {
    
        @Value("${jdbc.database.driver}")
        private String driver = null;
        @Value("${jdbc.database.url}")
        private String url = null;
        @Value("${jdbc.database.username}")
        private String username = null;
        @Value("${jdbc.database.password}")
        private String password = null;
    
        @Bean(name = "dataSource2")
        public DataSource getDataSource() {
            Properties props = new Properties();
            props.setProperty("driver", driver);
            props.setProperty("url", url);
            props.setProperty("username", username);
            props.setProperty("password", password);
            DataSource dataSource = null;
            try {
                dataSource = (DataSource) BasicDataSourceFactory.createDataSource(props);
                System.out.println("-----dataSource2 init-----");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return dataSource;
        }
    
    }

    使用XML方式加载属性文件

      也可以使用XML方式进行加载属性文件,它只需要使用<con-text:property-placeholder>元素加载一些配置项即可。
      代码清单:通过XML加载属性文件

    <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">
    
        <context:component-scan base-package="com.ssm.chapter10.annotation"/>
    
        <!--<import resourse="spring-datasource.xml"/>-->
    
        <!--<context:property-placeholder ignore-resource-not-found="true" location="classpath:ssm/chapter10/database-config.properties"/>-->
    
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <!--字符串数组,可配置多个属性文件-->
            <property name="locations">
                <array>
                    <value>classpath:ssm/chapter10/database-config.properties</value>
                    <value>classpath:log4j.properties</value>
                </array>
            </property>
            <property name="ignoreResourceNotFound" value="false"/>
        </bean>
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
    </beans>
  • 相关阅读:
    第三百四十九、五十天 how can I 坚持
    第三百四十八天 how can I 坚持
    第三百四十七天 how can I 坚持
    第三百四十六天 how can I 坚持
    第三百四十五天 how can I 坚持
    第三百四十四天 how can I 坚持
    第三百四十三天 how can I 坚持
    第三百四十二天 how can I 坚持
    第三百四十一天 how can I 坚持
    POJ 2996:Help Me with the Game
  • 原文地址:https://www.cnblogs.com/ooo0/p/10981730.html
Copyright © 2011-2022 走看看