Java读取properties文件内容的几种方式详解

 更新时间:2023年11月07日 09:00:17   作者:JFS_Study  
这篇文章主要介绍了Java读取properties文件内容的几种方式详解,读取properties配置文件在实际的开发中使用的很多,本文来介绍常用的几种实现方式,需要的朋友可以参考下

Java读取properties文件内容的几种方式详解

一、通过context:property-placeholder

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

二、使用util:properties标签

使用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">

三、通过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结果
	@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静态代码块中读取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);
	}
}

说明:这样的话,在该类被加载的时候,它就会自动读取指定位置的配置文件内容并保存到静态属性中,高效且方便,一次加载,可多次使用。

五、使用注解的方式注入

使用注解的方式注入,主要用在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>

六、@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;

可以通过实现 EnvironmentAware 然后实现接口中的方法

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

到此这篇关于Java读取properties文件内容的几种方式详解的文章就介绍到这了,更多相关Java读取properties文件内容内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Springboot+Bootstrap实现增删改查实战

    Springboot+Bootstrap实现增删改查实战

    这篇文章主要介绍了Springboot+Bootstrap实现增删改查实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • idea中的Maven导包失败问题解决方案汇总

    idea中的Maven导包失败问题解决方案汇总

    这篇文章主要介绍了idea中的Maven导包失败问题解决总结,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-02-02
  • 使用Swagger2实现自动生成RESTful API文档

    使用Swagger2实现自动生成RESTful API文档

    在开发 RESTful API 的过程中,文档是非常重要的一部分,可以帮助开发者了解 API 的功能和使用方法,本文将使用Swagger2 实现自动生成 RESTful API 文档,需要的可以参考一下
    2023-06-06
  • 详解Springboot-MyBatis配置-配置端口号与服务路径(idea社区版2023.1.4+apache-maven-3.9.3-bin)

    详解Springboot-MyBatis配置-配置端口号与服务路径(idea社区版2023.1.4+apache-mav

    这篇文章主要介绍了Springboot-MyBatis配置-配置端口号与服务路径(idea社区版2023.1.4+apache-maven-3.9.3-bin),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • JDK10新特性之var泛型和多个接口实现方法

    JDK10新特性之var泛型和多个接口实现方法

    这篇文章主要介绍了JDK10的新特性:var泛型和多个接口实现方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05
  • Java中LinkedList和ArrayList的效率分析

    Java中LinkedList和ArrayList的效率分析

    本文主要介绍了Java中LinkedList和ArrayList的效率分析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • spring中的特殊注解@RequiredArgsConstructor详解

    spring中的特殊注解@RequiredArgsConstructor详解

    这篇文章主要介绍了spring中的特殊注解@RequiredArgsConstructor,包括注解注入,构造器注入及setter注入,结合示例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-04-04
  • Java Runtime类详解_动力节点Java学院整理

    Java Runtime类详解_动力节点Java学院整理

    Runtime类封装了运行时的环境。每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。下面通过本文给大家分享Java Runtime类详解,需要的朋友参考下吧
    2017-04-04
  • Spring MVC拦截器的基本使用方法

    Spring MVC拦截器的基本使用方法

    这篇文章主要给大家介绍了关于Spring MVC拦截器的基本使用方法,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring MVC具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-07-07
  • Java实现的读取资源文件工具类ResourcesUtil实例【可动态更改值的内容】

    Java实现的读取资源文件工具类ResourcesUtil实例【可动态更改值的内容】

    这篇文章主要介绍了Java实现的读取资源文件工具类ResourcesUtil,结合实例形式分析了java针对资源文件的读取与修改相关操作技巧,需要的朋友可以参考下
    2017-10-10

最新评论