spring 加載屬性(properties)文件

  在開發的過程當中,配置文件每每就是那些屬性(properties)文件,好比使用properties文件配置數據庫文件,又如database-config.properties
  代碼清單:database-config.propertiesjava

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的方式進行加載屬性文件mysql

 

使用註解方式加載屬性文件

  Spring提供了註解@PropertySource來加載屬性文件,瞭解它的配置項。
  •name:字符串,配置此次屬性配置的名稱。
  •value:字符串數組,能夠配置多個屬性文件。
  •ignoreResourceNotFound:boolean值,默認爲false,其含義爲若是找不到對應的屬性文件是否進行忽略處理,因爲默認值爲false,因此在默認的狀況下找不到對應的配置文件會拋出異常。
  •encoding:編碼,默認爲""。spring

  代碼清單:在Spring環境中使用屬性文件Java配置sql

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解析對應的屬性文件,並經過佔位符去引用對應的配置。apache

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加載屬性文件mvc

<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>
相關文章
相關標籤/搜索