大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節點LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 學習攻略 Java學習 Java讀取properties文件的方式

Java讀取properties文件的方式

更新時間:2022-07-18 12:57:55 來源:動力節點 瀏覽1655次

1.通過context:property-placeholder加載配置文件jdbc.properties中的內容

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

2.使用util:properties標簽進行暴露properties文件中的內容

<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">
\

3.通過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結果
	@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 注解注入即可。

4.自定義工具類PropertyUtil,并在該類的static靜態代碼塊中讀取properties文件內容保存在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文件內容.......");
		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("出現IOException");
		} finally {
			try {
				if(null != in) {
					in.close();
				}
			} catch (IOException e) {
				logger.error("jdbc.properties文件流關閉出現異常");
			}
		}
		logger.info("加載properties文件內容完成...........");
		logger.info("properties文件內容:" + 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);
	}
}

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

5.使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應的value值

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
 <!--  這里是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數組,跟上面一樣 -->
 <property name="locations">
    <array>
      <value>classpath:jdbc.properties</value>
    </array>
 </property>
</bean>

6.@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;

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

7.import org.springframework.core.env.Environment;

(1)如何引用這個類:

可以通過 @Autowired注入Environment

@Autowired
private Environment environment;

可以通過實現 EnvironmentAware 然后實現接口中的方法

@Setter
private Environment environment;

(2)常用功能

獲取屬性配制文件中的值:environment.getProperty("rabbitmq.address")

獲取是否使用profile的

public boolean isDev(){
    boolean devFlag = environment.acceptsProfiles("dev");
    return  devFlag;
}

8.@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
  ......
}

9.PropertySource(不常用)

@PropertySource 讀取指定 properties 文件

@Component
@PropertySource("classpath:website.properties")
class WebSite {
 @Value("${url}")
 private String url;
  省略getter/setter
  ......
}

 

提交申請后,顧問老師會電話與您溝通安排學習

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 日韩精品片| 久久青草免费免费91线频观看 | 亚洲精品久久婷婷爱久久婷婷 | 日本黄页网站在线观看 | 成人免费视频国产 | 国产精品久久久久aaaa | 99热成人精品国产免男男 | 日日摸狠狠的摸夜夜摸 | 97免费在线视频 | 色88888久久久久久影院 | 久久久网久久久久合久久久久 | 亚洲成人精品在线 | 久久99精品久久久久久噜噜 | 好吊妞操| 四虎免费在线观看视频 | 国产欧美日本亚洲精品五区 | 亚洲人成影院在线高清 | 九九精品视频一区二区三区 | 伊人天天干 | 精品一精品国产一级毛片 | 久久天天躁狠狠躁狠狠躁 | 亚洲www色 | 最新亚洲精品国自产在线观看 | 国产又色又爽又黄又刺激18 | 在线综合色 | 亚洲国产成人九九综合 | 风流一代在线播放 | 99热亚洲| 欧美肥婆xxxx欧美另类 | 国内精品久久影院 | 99久久久久国产 | 欧美亚洲国产成人综合在线 | 亚洲狠狠婷婷综合久久久图片 | 奇米色影院 | 亚洲免费视频网 | 一级二级毛片 | 久久这里只有精品久久 | 久久精品福利视频 | 在线观看 中文字幕 | 久草新免费 | 91大学生视频 |