大战熟女丰满人妻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
  ......
}

 

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

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 久久精品123| 国产l精品国产亚洲区久久 国产l精品国产亚洲区在线观看 | 成人亚洲国产精品久久 | 伊人狠狠丁香婷婷综合色 | 日韩大片 | 欧美日韩一本大道香蕉欧美 | 亚洲观看视频 | 四虎网址在线 | 国产精品乱 | 青青热久久国产久精品 | 亚洲精品久久麻豆蜜桃 | 欧美久在线观看在线观看 | 日韩手机看片 | 久久精品亚洲综合一品 | 免费看美女吃男生私人部位 | 国产亚洲精品资源一区 | 国产xxxx做受性欧美88 | 天天操天天干天天爱 | 最新国产区 | 丁香午夜婷婷 | 色婷婷狠狠五月综合天色拍 | 香蕉网站男人网站 | 久热首页 | 日韩精品成人 | 欧美成人一区二区三区在线电影 | 色综合久久综精品 | 国产香蕉视频在线播放 | 欧美日韩片 | 亚洲综合成人网在线观看 | 国产综合精品久久亚洲 | 夜夜爽夜夜叫夜夜高潮漏水 | 久久综合激情 | 综合亚洲欧美日韩一区二区 | 免费观看a级完整视频 | 国产一区精品在线 | 亚洲综合射 | 日本一级毛片片免费观看 | 久久婷婷国产麻豆91天堂 | 久久精品亚洲日本筱田优 | 日日天干夜夜人人添 | 国产自愉怕一区二区三区 |