java读取properties常见的三种方式
方式一:
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created with IDEA
* author: bigStone
* Date:2019/4/20
* Time:16:52
*/
public class LoadProperties {
@Test
public void test(){
try {
InputStream resourceAsStream = Class.class.getResourceAsStream("/config/default.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
System.out.println(properties.getProperty("PAGESIZE"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
方式二:
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.Properties;
/**
* Created with IDEA
* author: bigStone
* Date:2019/4/20
* Time:16:52
*/
public class LoadProperties {
@Test
public void test() {
try {
ClassPathResource classPathResource = new ClassPathResource("/config/default.properties");
Properties properties = PropertiesLoaderUtils.loadProperties(classPathResource);
System.out.println(properties.getProperty("PAGESIZE"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
方式三: 通过@value注解获取文件中的属性
在spring中引入properties文件:
(因为要加载两个properties文件,想到用通配符,测试可以用。
版本号为: struts2.5.10, spring4.3.8, hibernate5.1.7 )
<context:property-placeholder location="classpath:config/*.properties"/>
注意:用 @Compoment, @Value 注解把类和该类的属性都交给spring来管理。所以取属性值的时候,也应该用spring容器中的对象来取值。
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
/**
* Created with IDEA
* author: bigStone
* Date:2019/4/20
* Time:16:52
*/
@Component
public class LoadProperties {
@Value("${PAGESIZE}")
public String pageSize;
@Test
public void test1(){
ApplicationContext ac = new ClassPathXmlApplicationContext("config/spring/applicationContext.xml");
LoadProperties loadProperties = (LoadProperties) ac.getBean("loadProperties");
System.out.println(loadProperties.pageSize);
}
}