一個系統(tǒng)中通常會存在如下一些以Properties形式存在的配置文件

成都創(chuàng)新互聯(lián)公司專業(yè)IDC數(shù)據(jù)服務器托管提供商,專業(yè)提供成都服務器托管,服務器租用,成都多線機房,成都多線機房,成都多線服務器托管等服務器托管服務。
1.數(shù)據(jù)庫配置文件demo-db.properties:
database.url=jdbc:MySQL://localhost/smaple database.driver=com.mysql.jdbc.Driver database.user=root database.password=123
2.消息服務配置文件demo-mq.properties:
#congfig of ActiveMQ mq.java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory mq.java.naming.provider.url=failover:(tcp://localhost:61616?soTimeout=30000&connectionTimeout=30000)?jms.useAsyncSend=true&timeout=30000 mq.java.naming.security.principal= mq.java.naming.security.credentials= jms.MailNotifyQueue.consumer=5
3.遠程調用的配置文件demo-remote.properties:
remote.ip=localhost remote.port=16800 remote.serviceName=test
一、系統(tǒng)中需要加載多個Properties配置文件
應用場景:Properties配置文件不止一個,需要在系統(tǒng)啟動時同時加載多個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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 將多個配置文件讀取到容器中,交給Spring管理 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- 這里支持多種尋址方式:classpath和file -->
<value>classpath:/opt/demo/config/demo-db.properties</value>
<!-- 推薦使用file的方式引入,這樣可以將配置和代碼分離 -->
<value>file:/opt/demo/config/demo-mq.properties</value>
<value>file:/opt/demo/config/demo-remote.properties</value>
</list>
</property>
</bean>
<!-- 使用MQ中的配置 -->
<bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>
<prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>
<prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>
<prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>
<prop key="userName">${mq.java.naming.security.principal}</prop>
<prop key="password">${mq.java.naming.security.credentials}</prop>
</props>
</property>
</bean>
</beans> 我們也可以將配置中的List抽取出來:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 將多個配置文件位置放到列表中 -->
<bean id="propertyResources" class="java.util.ArrayList">
<constructor-arg>
<list>
<!-- 這里支持多種尋址方式:classpath和file -->
<value>classpath:/opt/demo/config/demo-db.properties</value>
<!-- 推薦使用file的方式引入,這樣可以將配置和代碼分離 -->
<value>file:/opt/demo/config/demo-mq.properties</value>
<value>file:/opt/demo/config/demo-remote.properties</value>
</list>
</constructor-arg>
</bean>
<!-- 將配置文件讀取到容器中,交給Spring管理 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" ref="propertyResources" />
</bean>
<!-- 使用MQ中的配置 -->
<bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>
<prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>
<prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>
<prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>
<prop key="userName">${mq.java.naming.security.principal}</prop>
<prop key="password">${mq.java.naming.security.credentials}</prop>
</props>
</property>
</bean>
</beans> 二、整合多工程下的多個分散的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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 將DB屬性配置文件位置放到列表中 -->
<bean id="dbResources" class="java.util.ArrayList">
<constructor-arg>
<list>
<value>file:/opt/demo/config/demo-db.properties</value>
</list>
</constructor-arg>
</bean>
<!-- 將MQ屬性配置文件位置放到列表中 -->
<bean id="mqResources" class="java.util.ArrayList">
<constructor-arg>
<list>
<value>file:/opt/demo/config/demo-mq.properties</value>
</list>
</constructor-arg>
</bean>
<!-- 用Spring加載和管理DB屬性配置文件 -->
<bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations" ref="dbResources" />
</bean>
<!-- 用Spring加載和管理MQ屬性配置文件 -->
<bean id="mqPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="2" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations" ref="mqResources" />
</bean>
<!-- 使用DB中的配置屬性 -->
<bean id="rmsDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${demo.db.driver}" p:url="${demo.db.url}" p:username="${demo.db.username}"
p:password="${demo.db.password}" pp:maxActive="${demo.db.maxactive}"p:maxWait="${demo.db.maxwait}"
p:poolPreparedStatements="true" p:defaultAutoCommit="false">
</bean>
<!-- 使用MQ中的配置 -->
<bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>
<prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>
<prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>
<prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>
<prop key="userName">${mq.java.naming.security.principal}</prop>
<prop key="password">${mq.java.naming.security.credentials}</prop>
</props>
</property>
</bean>
</beans> 注意:其中order屬性代表其加載順序,而ignoreUnresolvablePlaceholders為是否忽略不可解析的 Placeholder,如配置了多個PropertyPlaceholderConfigurer,則需設置為true。這里一定需要按照這種方式設置這兩個參數(shù)。
三、Bean中直接注入Properties配置文件中的值
應用場景:Bean中需要直接注入Properties配置文件中的值 。例如下面的代碼中需要獲取上述demo-remote.properties中的值:
public class Client() {
private String ip;
private String port;
private String service;
} 配置如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="<a rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/beans</a>" xmlns:xsi="<a rel="external nofollow" >http://www.w3.org/2001/XMLSchema-instance</a>" xmlns:util="<a rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/util</a>" xsi:schemaLocation=" <a rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/beans</a> <a rel="external nofollow" >http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</a> <a rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/util</a> <a rel="external nofollow" >http://www.springframework.org/schema/util/spring-util-3.0.xsd</a>"> <!-- 這種加載方式可以在代碼中通過@Value注解進行注入, 可以將配置整體賦給Properties類型的類變量,也可以取出其中的一項賦值給String類型的類變量 --> <!-- <util:properties/> 標簽只能加載一個文件,當多個屬性文件需要被加載的時候,可以使用多個該標簽 --> <util:properties id="remoteSettings" location="file:/opt/demo/config/demo-remote.properties" /> <!-- <util:properties/> 標簽的實現(xiàn)類是PropertiesFactoryBean, 直接使用該類的bean配置,設置其locations屬性可以達到一個和上面一樣加載多個配置文件的目的 --> <bean id="settings" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>file:/opt/rms/config/rms-mq.properties</value> <value>file:/opt/rms/config/rms-env.properties</value> </list> </property> </bean> </beans>
Client類中使用Annotation如下:
import org.springframework.beans.factory.annotation.Value;
public class Client() {
@Value("#{remoteSettings['remote.ip']}")
private String ip;
@Value("#{remoteSettings['remote.port']}")
private String port;
@Value("#{remoteSettings['remote.serviceName']}")
private String service;
}四、Bean中存在Properties類型的類變量
應用場景:當Bean中存在Properties類型的類變量需要以注入的方式初始化
1. 配置方式:我們可以用(三)中的配置方式,只是代碼中注解修改如下
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
public class Client() {
@Value("#{remoteSettings}")
private Properties remoteSettings;
} 2. 配置方式:也可以使用xml中聲明Bean并且注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 可以使用如下的方式聲明Properties類型的FactoryBean來加載配置文件,這種方式就只能當做Properties屬性注入,而不能獲其中具體的值 -->
<bean id="remoteConfigs" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>file:/opt/demo/config/demo-remote.properties</value>
</list>
</property>
</bean>
<!-- 遠端調用客戶端類 -->
<bean id="client" class="com.demo.remote.Client">
<property name="properties" ref="remoteConfigs" />
</bean>
</beans> 代碼如下:
import org.springframework.beans.factory.annotation.Autowired;
public class Client() {
//@Autowired也可以使用
private Properties remoteSettings;
//getter setter
} 上述的各個場景在項目群中特別有用,需要靈活的使用上述各種配置方式。
在很多情況下我們需要在配置文件中配置一些屬性,然后注入到bean中,Spring提供了org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer類,可以方便我們使用注解直接注入properties文件中的配置。
下面我們看下具體如何操作:
首先要新建maven項目,并在pom文件中添加spring依賴,如下pom.xml文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.outofmemory</groupId>
<artifactId>hellospring.properties.annotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hellospring.properties.annotation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework-version>3.0.0.RC2</org.springframework-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
</dependencies>
</project>要自動注入properties文件中的配置,需要在spring配置文件中添加org.springframework.beans.factory.config.PropertiesFactoryBean和org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer的實例配置:
如下spring配置文件appContext.xml
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
<!-- bean annotation driven -->
<context:annotation-config />
<context:component-scan base-package="cn.outofmemory.hellospring.properties.annotation">
</context:component-scan>
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:application.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
</beans>在這個配置文件中我們配置了注解掃描,和configProperties實例和propertyConfigurer實例。這樣我們就可以在java類中自動注入配置了,我們看下java類中如何做:
package cn.outofmemory.hellospring.properties.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MySQLConnectionInfo {
@Value("#{configProperties['mysql.url']}")
private String url;
@Value("#{configProperties['mysql.userName']}")
private String userName;
@Value("#{configProperties['mysql.password']}")
private String password;
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
}自動注入需要使用@Value注解,這個注解的格式#{configProperties['mysql.url']}其中configProperties是我們在appContext.xml中配置的beanId,mysql.url是在properties文件中的配置項。
properties文件的內容如下:
mysql.url=mysql's url mysql.userName=mysqlUser mysql.password=mysqlPassword
最后我們需要測試一下以上寫法是否有問題,如下App.java文件內容:
package cn.outofmemory.hellospring.properties.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");
MySQLConnectionInfo connInfo = appContext.getBean(MySQLConnectionInfo.class);
System.out.println(connInfo.getUrl());
System.out.println(connInfo.getUserName());
System.out.println(connInfo.getPassword());
}
}在main方法中首先聲明了appContext,然后獲得了自動注入的MySQLConnectionInfo的實例,然后打印出來,運行程序會輸出配置文件中配置的值
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對創(chuàng)新互聯(lián)的支持。如果你想了解更多相關內容請查看下面相關鏈接
本文名稱:Spring加載配置和讀取多個Properties文件的講解
文章網(wǎng)址:http://chinadenli.net/article32/gdepsc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、企業(yè)網(wǎng)站制作、域名注冊、ChatGPT、靜態(tài)網(wǎng)站、
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)