Java讀取properties文件內(nèi)容的幾種方式詳解
Java讀取properties文件內(nèi)容的幾種方式詳解
一、通過context:property-placeholder
通過context:property-placeholder加載配置文件jdbc.properties中的內(nèi)容
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
上面的配置和下面配置等價(jià),是對(duì)下面配置的簡化:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean>
<!-- 配置組件掃描,springmvc容器中只掃描Controller注解 --> <context:component-scan base-package="com.zxt.www" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
二、使用util:properties標(biāo)簽
使用util:properties標(biāo)簽進(jìn)行暴露properties文件中的內(nèi)容
<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>
注意:使用上面這行配置,需要在spring-dao.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" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
三、通過PropertyPlaceholderConfigurer
通過PropertyPlaceholderConfigurer在加載上下文的時(shí)候暴露properties到自定義子類的屬性中以供程序中使用
<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="ignoreResourceNotFound" value="true"/> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean>
自定義類 PropertyConfigurer 的聲明如下:
/** * Desc:properties配置文件讀取類 */ public class PropertyConfigurer extends PropertyPlaceholderConfigurer { private Properties props; // 存取properties配置文件key-value結(jié)果 @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); this.props = props; } public String getProperty(String key){ return this.props.getProperty(key); } public String getProperty(String key, String defaultValue) { return this.props.getProperty(key, defaultValue); } public Object setProperty(String key, String value) { return this.props.setProperty(key, value); } }
使用方式:在需要使用的類中使用 @Autowired 注解注入即可。
四、自定義工具類PropertyUtil
自定義工具類PropertyUtil,并在該類的static靜態(tài)代碼塊中讀取properties文件內(nèi)容保存在static屬性中以供別的程序使用
/** * Desc:properties文件獲取工具類 */ public class PropertyUtil { private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class); private static Properties props; static{ loadProps(); } synchronized static private void loadProps(){ logger.info("開始加載properties文件內(nèi)容......."); props = new Properties(); InputStream in = null; try { <!--第一種,通過類加載器進(jìn)行獲取properties文件流--> in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); <!--第二種,通過類進(jìn)行獲取properties文件流--> //in = PropertyUtil.class.getResourceAsStream("/jdbc.properties"); props.load(in); } catch (FileNotFoundException e) { logger.error("jdbc.properties文件未找到"); } catch (IOException e) { logger.error("出現(xiàn)IOException"); } finally { try { if(null != in) { in.close(); } } catch (IOException e) { logger.error("jdbc.properties文件流關(guān)閉出現(xiàn)異常"); } } logger.info("加載properties文件內(nèi)容完成..........."); logger.info("properties文件內(nèi)容:" + props); } public static String getProperty(String key){ if(null == props) { loadProps(); } return props.getProperty(key); } public static String getProperty(String key, String defaultValue) { if(null == props) { loadProps(); } return props.getProperty(key, defaultValue); } }
說明:這樣的話,在該類被加載的時(shí)候,它就會(huì)自動(dòng)讀取指定位置的配置文件內(nèi)容并保存到靜態(tài)屬性中,高效且方便,一次加載,可多次使用。
五、使用注解的方式注入
使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應(yīng)的value值
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <!-- 這里是PropertiesFactoryBean類,它也有個(gè)locations屬性,也是接收一個(gè)數(shù)組,跟上面一樣 --> <property name="locations"> <array> <value>classpath:jdbc.properties</value> </array> </property> </bean>
六、@Value(常用)
application.properties 配置文件
string.port=1111 integer.port=1111 db.link.url=jdbc:mysql://localhost:3306/test db.link.driver=com.mysql.jdbc.Driver db.link.username=root db.link.password=root
類文件:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyConf { @Value("${string.port}") private int intPort; @Value("${string.port}") private String stringPort; @Value("${db.link.url}") private String dbUrl; @Value("${db.link.driver}") private String dbDriver; @Value("${db.link.username}")private String dbUsername; @Value("${db.link.password}")private String dbPassword; public void show(){ System.out.println("======================================"); System.out.println("intPort : " + (intPort + 1111)); System.out.println("stringPort : " + (stringPort + 1111)); System.out.println("string : " + dbUrl); System.out.println("string : " + dbDriver); System.out.println("string : " + dbUsername); System.out.println("string : " + dbPassword); System.out.println("======================================"); } }
- 類名上指定配置文件@PropertySource可以聲明多個(gè),或者使用@PropertySources(@PropertySource(“xxx”),@PropertySource(“xxx”))。
- 在bean中使用@value注解獲取配置文件的值
@Value("${key}") private Boolean timerEnabled;
即使給變量賦了初值也會(huì)以配置文件的值為準(zhǔn)。
七、Environment
import org.springframework.core.env.Environment
如何引用這個(gè)類:
可以通過 @Autowired注入Environment
@Autowired private Environment environment;
可以通過實(shí)現(xiàn) EnvironmentAware 然后實(shí)現(xiàn)接口中的方法
@Setter private Environment environment;
常用功能
- 獲取屬性配制文件中的值:environment.getProperty("rabbitmq.address")
- 獲取是否使用profile的
public boolean isDev(){ boolean devFlag = environment.acceptsProfiles("dev"); return devFlag; }
八、@ConfigurationProperties(常用)
通過@ConfigurationProperties讀取配置信息并與 bean 綁定,可以像使用普通的 Spring bean 一樣,將其注入到類中使用。
@Component @ConfigurationProperties(prefix = "library") class LibraryProperties { @NotEmpty private String location; private List<Book> books; @Setter @Getter @ToString static class Book { String name; String description; } //省略getter/setter ...... }
九、PropertySource(不常用)
@PropertySource 讀取指定 properties 文件
@Component @PropertySource("classpath:website.properties") class WebSite { @Value("${url}") private String url; 省略getter/setter ...... }
到此這篇關(guān)于Java讀取properties文件內(nèi)容的幾種方式詳解的文章就介紹到這了,更多相關(guān)Java讀取properties文件內(nèi)容內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
學(xué)習(xí)SpringMVC——國際化+上傳+下載詳解
本篇文章主要介紹了學(xué)習(xí)SpringMVC——國際化+上傳+下載,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。2016-12-12Thymeleaf對(duì)象的使用之基本對(duì)象實(shí)例解析
這篇文章主要介紹了Thymeleaf對(duì)象的使用之基本對(duì)象實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04Java面試之動(dòng)態(tài)規(guī)劃與組合數(shù)
這篇文章主要介紹了Java面試之動(dòng)態(tài)規(guī)劃與組合數(shù)的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09Java實(shí)現(xiàn)插入排序算法可視化的示例代碼
插入排序的算法描述是一種簡單直觀的排序算法。其原理是通過構(gòu)建有序序列,對(duì)于未排序數(shù)據(jù),在已排序序列中從后向前掃描,找到相應(yīng)位置并插入。本文將用Java語言實(shí)現(xiàn)插入排序算法并進(jìn)行可視化,感興趣的可以了解一下2022-08-08