最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java讀取properties文件內(nèi)容的幾種方式詳解

 更新時間:2023年11月07日 09:00:17   作者:JFS_Study  
這篇文章主要介紹了Java讀取properties文件內(nèi)容的幾種方式詳解,讀取properties配置文件在實際的開發(fā)中使用的很多,本文來介紹常用的幾種實現(xiàn)方式,需要的朋友可以參考下

Java讀取properties文件內(nèi)容的幾種方式詳解

一、通過context:property-placeholder

通過context:property-placeholder加載配置文件jdbc.properties中的內(nèi)容

<context:property-placeholder location="classpath:jdbc.properties" 
ignore-unresolvable="true"/>

上面的配置和下面配置等價,是對下面配置的簡化:

<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標簽

使用util:properties標簽進行暴露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在加載上下文的時候暴露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 {
			<!--第一種,通過類加載器進行獲取properties文件流-->
			in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
			<!--第二種,通過類進行獲取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);
	}
}

說明:這樣的話,在該類被加載的時候,它就會自動讀取指定位置的配置文件內(nèi)容并保存到靜態(tài)屬性中,高效且方便,一次加載,可多次使用。

五、使用注解的方式注入

使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應(yīng)的value值

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
 <!--  這里是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數(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可以聲明多個,或者使用@PropertySources(@PropertySource(“xxx”),@PropertySource(“xxx”))。
  • 在bean中使用@value注解獲取配置文件的值
@Value("${key}")
private Boolean timerEnabled;

即使給變量賦了初值也會以配置文件的值為準。

七、Environment

import org.springframework.core.env.Environment

如何引用這個類:

可以通過 @Autowired注入Environment

@Autowired
private Environment environment;

可以通過實現(xiàn) EnvironmentAware 然后實現(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java三目運算中隱藏的自動拆裝箱

    Java三目運算中隱藏的自動拆裝箱

    這篇文章主要介紹了Java三目運算中隱藏的自動拆裝箱,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-11-11
  • Spring MVC如何設(shè)置響應(yīng)

    Spring MVC如何設(shè)置響應(yīng)

    本文介紹了如何在Spring框架中設(shè)置響應(yīng),并通過不同的注解返回靜態(tài)頁面、HTML片段和JSON數(shù)據(jù),此外,還講解了如何設(shè)置響應(yīng)的狀態(tài)碼和Header
    2025-01-01
  • java中break和continue區(qū)別及使用場合分析

    java中break和continue區(qū)別及使用場合分析

    本文力圖通過實例加使用場合詳解來引導(dǎo)菜鳥重新認識break和continue語句,需要的朋友可以參考下
    2014-01-01
  • Mybatis返回數(shù)組的兩種實現(xiàn)方式

    Mybatis返回數(shù)組的兩種實現(xiàn)方式

    這篇文章主要介紹了Mybatis返回數(shù)組的兩種實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • Java底層基于鏈表實現(xiàn)集合和映射--集合Set操作詳解

    Java底層基于鏈表實現(xiàn)集合和映射--集合Set操作詳解

    這篇文章主要介紹了Java底層基于鏈表實現(xiàn)集合和映射集合Set操作,結(jié)合實例形式詳細分析了Java使用鏈表實現(xiàn)集合和映射相關(guān)原理、操作技巧與注意事項,需要的朋友可以參考下
    2020-03-03
  • springboot @ConditionalOnMissingBean注解的作用詳解

    springboot @ConditionalOnMissingBean注解的作用詳解

    這篇文章主要介紹了springboot @ConditionalOnMissingBean注解的作用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • java命令打jar包詳細步驟示例講解

    java命令打jar包詳細步驟示例講解

    對于如何將一個java文件通過命令形式進行打包,通過以下示例進行講解,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-12-12
  • Java自旋鎖與讀寫鎖的實現(xiàn)原理

    Java自旋鎖與讀寫鎖的實現(xiàn)原理

    本文介紹了Java中的自旋鎖和讀寫鎖,自旋鎖是一種非阻塞鎖,適用于鎖持有時間極短的場景,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2026-02-02
  • jmeter的時間戳函數(shù)使用

    jmeter的時間戳函數(shù)使用

    在使用jmeter做接口測試的時候,經(jīng)常會要用到日期這種函數(shù),本文主要介紹了jmeter的時間戳函數(shù)使用,感興趣的可以了解一下
    2021-11-11
  • Java LocalDateTime轉(zhuǎn)Json報錯處理方案

    Java LocalDateTime轉(zhuǎn)Json報錯處理方案

    在使用LocalDateTime進行JSON轉(zhuǎn)換時,需添加Jackson JSR310模塊并配置注解,或通過自定義工具處理,解決序列化異常問題
    2025-07-07

最新評論

河源市| 策勒县| 抚顺县| 乌拉特前旗| 磐安县| 承德县| 玉山县| 乳山市| 彭阳县| 永康市| 阳朔县| 桐梓县| 淳化县| 平遥县| 如皋市| 阜阳市| 阳原县| 鹿泉市| 天镇县| 叙永县| 蓝田县| 河南省| 崇阳县| 积石山| 岚皋县| 兴国县| 略阳县| 德令哈市| 城步| 堆龙德庆县| 利辛县| 抚顺县| 拉孜县| 沁阳市| 景泰县| 桐乡市| 峨眉山市| 广宁县| 襄汾县| 郴州市| 鲁甸县|