获取properties配置
1. 使用@Value
@Value("${swagger.enable}")
使用Spring的PropertyPlaceholderConfigurer关联 @Value
方法一:使用xml配置PropertyPlaceholderConfigurer,使用@ContextConfiguration导入配置文件
package com.properties.value;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import lombok.extern.slf4j.Slf4j;
//方法一:使用xml配置PropertyPlaceholderConfigurer,使用@ContextConfiguration导入配置文件
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationCtx.xml")
@Slf4j
public class ValueUsage1 {
@Value("${username}")
private String uname;
@Value("${password}")
private String pwd;
@Test
public void test(){
log.info("username:"+uname);
log.info("password:"+pwd);
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 对于读取一个配置文件采取的方案 -->
<property name="location" value="classpath:cfg.properties"></property>
<!-- 对于读取两个以上配置文件采取的处理方案 -->
<!--
<property name="locations">
<list>
<value>classpath:cfg.properties</value>
<value>classpath:cfg2.properties</value>
</list>
</property>
-->
</bean>
</beans>
username=jay
password=123
env=${pom.env}
ver=${pom.ver}
方法二:使用@Bean实例化PropertySourcesPlaceholderConfigurer,@PropertySources导入资源
package com.properties.value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//方法二:使用@Bean实例化PropertySourcesPlaceholderConfigurer,@PropertySources导入资源
public class ValueUsage2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(PropertiesWithJavaConfig.class);
FileService service = (FileService) annotationConfigApplicationContext.getBean("fileService");
service.readValues();
annotationConfigApplicationContext.close();
}
}
package com.properties.value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySources({ @PropertySource(value = "classpath:cfg.properties", ignoreResourceNotFound = true),
@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true) })
//==> @PropertySource("file:${app.home}/app.properties") file指向绝对路径
@ComponentScan(basePackages = "com.properties.value")
public class PropertiesWithJavaConfig {
//要想使用@Value 用${}占位符注入属性,这个bean是必须的,这个就是占位bean,另一种方式是不用value直接用Envirment变量直接getProperty('key')
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
#springfox.documentation.swagger.v2.path=/api-docs
#server.contextPath=/v2
server.port=8080
swagger.enable=true
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/websystique
jdbc.username = myuser
jdbc.password = mypassword
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
sourceLocation =/dev/input
destination =c\:/temp/output
username=jay
password=123
env=${pom.env}
ver=${pom.ver}
2. 使用Environment
@Autowired
private Environment environment;
environment.getProperty("swagger.enable")
方法一:@Inject或者@Autowired一个Environment对象
package com.properties.environment;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//方法一:@Inject或者@Autowired一个Environment对象
public class EnvironmentUsage1 {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(PropertiesWithJavaConfig.class);
FileService service = (FileService) annotationConfigApplicationContext.getBean("fileService");
service.readValues();
annotationConfigApplicationContext.close();
}
}
package com.properties.environment;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value = { "classpath:cfg.properties", "classpath:application.properties" })
@ComponentScan(basePackages = "com.properties.environment")
public class PropertiesWithJavaConfig {
}
package com.properties.environment;
public interface FileService {
public void readValues();
}
package com.properties.environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@Service("fileService")
public class FileServiceImpl implements FileService {
@Autowired
private Environment environment;
public void readValues() {
System.out.println("Getting property via Spring Environment :" + environment.getProperty("jdbc.driverClassName"));
System.out.println("Source Location : " + environment.getProperty("sourceLocation"));
System.out.println("Destination Location : " + environment.getProperty("destination"));
}
}
#springfox.documentation.swagger.v2.path=/api-docs
#server.contextPath=/v2
server.port=8080
swagger.enable=true
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/websystique
jdbc.username = myuser
jdbc.password = mypassword
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
sourceLocation =/dev/input
destination =c\:/temp/output
username=jay
password=123
env=${pom.env}
ver=${pom.ver}
方法二:实现EnvironmentAware接口
package com.properties.environment;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
//方法二:实现EnvironmentAware接口
@ComponentScan(basePackages = "com.properties.environment")
@SpringBootApplication
public class EnvironmentUsage2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(EnvironmentBean.class);
annotationConfigApplicationContext.refresh();
Environment environment = annotationConfigApplicationContext.getBean("environment2",Environment.class);
System.out.println("Getting property via Spring Environment :" + environment.getProperty("jdbc.driverClassName"));
System.out.println("Source Location : " + environment.getProperty("sourceLocation"));
System.out.println("Destination Location : " + environment.getProperty("destination"));
annotationConfigApplicationContext.close();
}
}
package com.properties.environment;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource(value = { "classpath:cfg.properties", "classpath:application.properties" })
public class EnvironmentBean implements EnvironmentAware {
private Environment environment2;
@Override
public void setEnvironment(Environment environment) {
this.environment2=environment;
}
@Bean(name="environment2")
public Environment readEnvironment() {
return environment2;
}
}
#springfox.documentation.swagger.v2.path=/api-docs
#server.contextPath=/v2
server.port=8080
swagger.enable=true
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/websystique
jdbc.username = myuser
jdbc.password = mypassword
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
sourceLocation =/dev/input
destination =c\:/temp/output
username=jay
password=123
env=${pom.env}
ver=${pom.ver}
3. pom中
<properties>
<springfox.version>2.8.0</springfox.version>
</properties>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox.version}</version>
</dependency>
4. 使用system.load properties
java.util.Properties
package com.properties.util;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class PropertiesUsage {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
try (InputStream resourceAsStream = PropertiesUsage.class.getClassLoader().getResourceAsStream("application.properties");
InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream,"UTF-8");){
properties.load(inputStreamReader);
System.out.println(properties.getProperty("hibernate.dialect"));
}
}
}
5. commons-configuration
package com.properties.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PropertiesConfigUtil {
public static final String PROPS_SUFFIX = ".properties";
private static Map<String, PropertiesConfiguration> configMap = new ConcurrentHashMap<String, PropertiesConfiguration>();
private static PropertiesConfiguration getConfig(String configName) {
// 去除空格
configName = configName.trim();
// 有后缀使用后缀 没后缀 添加后缀
String configSig = StringUtils.endsWith(configName, PROPS_SUFFIX) ? configName : configName + PROPS_SUFFIX;
if (configMap.containsKey(configSig)) {
return configMap.get(configSig);
}
PropertiesConfiguration config = null;
try {
config = new PropertiesConfiguration();
config.setEncoding("UTF-8");
config.load(configSig);
// 默认五秒检查一次
config.setReloadingStrategy(new FileChangedReloadingStrategy());
config.setThrowExceptionOnMissing(true);
configMap.put(configSig, config);
} catch (ConfigurationException e) {
e.printStackTrace();
}
return config;
}
public static Map<String, String> getKeyValuePairs(String configSig) {
PropertiesConfiguration config = getConfig(configSig);
if (config == null) {
return null;
}
Iterator<String> iters = config.getKeys();
Map<String, String> retMap = new HashMap<String, String>();
while (iters.hasNext()) {
String beforeKey = iters.next();
if (retMap.containsKey(beforeKey)) {
log.warn(configSig + " configKey:" + beforeKey + " repeated!!");
}
retMap.put(beforeKey, config.getString(beforeKey));
}
return retMap;
}
/**
* 通过PropertiesConfiguration取得参数的方法
* <p>
*
* @return 。
*/
static public String getString(String configSig, String key) {
return getConfig(configSig).getString(key);
}
static public String getString(String configSig, String key, String defaultValue) {
return getConfig(configSig).getString(key, defaultValue);
}
static public int getInt(String configSig, String key) {
return getConfig(configSig).getInt(key);
}
static public int getInt(String configSig, String key, int defaultValue) {
return getConfig(configSig).getInt(key, defaultValue);
}
static public boolean getBoolean(String configSig, String key) {
return getConfig(configSig).getBoolean(key);
}
static public boolean getBoolean(String configSig, String key, boolean defaultValue) {
return getConfig(configSig).getBoolean(key, defaultValue);
}
static public double getDouble(String configSig, String key) {
return getConfig(configSig).getDouble(key);
}
static public double getDouble(String configSig, String key, double defaultValue) {
return getConfig(configSig).getDouble(key, defaultValue);
}
static public float getFloat(String configSig, String key) {
return getConfig(configSig).getFloat(key);
}
static public float getFloat(String configSig, String key, float defaultValue) {
return getConfig(configSig).getFloat(key, defaultValue);
}
static public long getLong(String configSig, String key) {
return getConfig(configSig).getLong(key);
}
static public long getLong(String configSig, String key, long defaultValue) {
return getConfig(configSig).getLong(key, defaultValue);
}
static public short getShort(String configSig, String key) {
return getConfig(configSig).getShort(key);
}
static public short getShort(String configSig, String key, short defaultValue) {
return getConfig(configSig).getShort(key, defaultValue);
}
static public List<Object> getList(String configSig, String key) {
return getConfig(configSig).getList(key);
}
static public List<Object> getList(String configSig, String key, List<Object> defaultValue) {
return getConfig(configSig).getList(key, defaultValue);
}
static public byte getByte(String configSig, String key) {
return getConfig(configSig).getByte(key);
}
static public byte getByte(String configSig, String key, byte defaultValue) {
return getConfig(configSig).getByte(key, defaultValue);
}
static public String[] getStringArray(String configSig, String key) {
return getConfig(configSig).getStringArray(key);
}
}
package com.properties.util;
public class PropertiesConfigurationTest {
public static void main(String[] args) {
System.out.println(PropertiesConfigUtil.getString("application.properties", "hibernate.dialect"));
}
}
#springfox.documentation.swagger.v2.path=/api-docs
#server.contextPath=/v2
server.port=8080
swagger.enable=true
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/websystique
jdbc.username = myuser
jdbc.password = mypassword
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
sourceLocation =/dev/input
destination =c\:/temp/output
6. @ConfigurationProperties将properties导入到类中
package com.properties.configurationProperties;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
/*@EnableConfigurationProperties注解是用来开启对@ConfigurationProperties注解配置Bean的支持。
也就是@EnableConfigurationProperties注解告诉Spring Boot 使能支持@ConfigurationProperties*/
/*@ConfigurationProperties注解和@EnableConfigurationProperties配合使用*/
@SpringBootApplication
@EnableConfigurationProperties
public class DemoApplication {
public static void main(String[] args) {
try(ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(DemoApplication.class, args);){
RedisProps redisProps = configurableApplicationContext.getBean(RedisProps.class);
System.out.println(ReflectionToStringBuilder.toString(redisProps));
}
}
}
package com.properties.configurationProperties;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
@Component
@PropertySource("classpath:application.yml")
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RedisProps {
private int dbIndex;
@NotNull
private String hostname;
private String password;
@NotNull
private int port;
private long timeout;
private List<Map<String, String>> poolConfig;
}
spring:
redis:
dbIndex: 0
hostName: 192.168.58.133
password: nmamtf
port: 6379
timeout: 0
poolConfig:
- maxIdle: 8
- minIdle: 0
- maxActive: 8
- maxWait: -1
7. 使用第三方jar,比如Archaius
获取properties配置的更多相关文章
- 获取.properties配置文件属性值
public class TestProperties { /** * * @Title: printAllProperty * @Description: 输出所有配置信息 * @param pro ...
- 如何快速获取properties中的配置属性值
本文为博主原创,未经博主允许,不得转载: 在项目中,经常需要将一些配置的常量信息放到properties文件中,这样在项目的配置变动的时候,只需要修改配置文件中 对应的配置常量即可. 在项目应用中,如 ...
- @Value 注解获取properties值
转自:使用Spring 3的@value简化配置文件的读取 Spring 3支持@value注解的方式获取properties文件中的配置值,大简化了读取配置文件的代码. 1.在application ...
- [坑]Spring利用注解@Value获取properties属性为null
今天在项目中想使用@Value来获取Springboot中properties中属性值. 场景:定义了一个工具类,想要获取一些配置参数,使用了@value来获取,但是死活也获取不到. 如何解决:在使用 ...
- Spring利用注解@Value获取properties属性为null
今天在项目中想使用@Value来获取Springboot中properties中属性值. 场景:定义了一个工具类,想要获取一些配置参数,使用了@value来获取,但是死活也获取不到. 如何解决:在使用 ...
- SpringBoot利用注解@Value获取properties属性为null
参考:https://www.cnblogs.com/zacky31/p/8609990.html 今天在项目中想使用@Value来获取Springboot中properties中属性值. 场景:定义 ...
- Struts2学习:Action获取properties文件的值
配置文件路径: 配置内容: 方法一: Action内被调用的函数添加下段代码: Properties props = new Properties(); props.load(UploadFileAc ...
- spring 通过@Value 获取properties文件中设置了属性 ,与@Value # 和$的区别
spring 获取 properties的值方法 在spring.xml中配置 很奇怪的是,在context-param 加载的spring.xml 不能使用 ${xxx} 必须交给Dispatche ...
- Spring在代码中获取properties文件属性
这里介绍两种在代码中获取properties文件属性的方法. 使用@Value注解获取properties文件属性: 1.因为在下面要用到Spring的<util />配置,所以,首先要在 ...
随机推荐
- 自动化测试入门指南(3)-- 入门demo
按照 自动化测试入门指南(2)-- 环境搭建搭建好环境后,我们继续一步步实现一个简单的入门例子 Step0. 安装Firefox浏览器(http://pan.baidu.com/s/1c00bw8g中 ...
- canvas设置长宽
Canvas元素默认宽 300px, 高 150px, 设置其宽高可以使用如下方法:方法一:1 <canvas width="500" height="500&qu ...
- stm32寄存器版学习笔记06 输入捕获(ETR脉冲计数)
STM32外部脉冲ETR引脚:TIM1-->PA12;TIMER2-->PA0:TIMER3-->PD2;TIMER4-->PE0… 1.TIM2 PA0计数 配置步骤 ①开启 ...
- Python学习-类
类是对象的模板或蓝图,类是对象的抽象化,对象是类的实例化 在python中,一个对象的特征也称为属性(attribute),它所具有的的行为也称为方法(method) 对象 = 属性(特征)+方法(行 ...
- mysql导入外部sql脚本的方法
版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/u011043843/article/details/29689853 导入的方法分为两种:一是採用图 ...
- 1G1核1M选择 Centos 32位 还是 Centos 64位?
前几天有个疑惑,现有一台云主机是 1G1核1M使用 Centos 64位会不有点浪费. 还专门发信息询问老大 Karson,老大说现 FastAdmin 都是三个1,也是 64 位的. 看 FastA ...
- (转)[Android实例] 关于使用ContentObserver监听不到删除短信会话的解决方案
最近做通讯录的项目,需要实时监听短信的删除,就用到了观察者ContentObserver,怪异的事情就此发生,当我删除一条短信的时候,可以监听到,但是,当我删除整条短信的时候,就无法监听到,查了很多资 ...
- laravel里面的控制器笔记
看了下教程,总结了下,大概分两种 一般的controller restful的controller 单独绑定action的route为 Route::get('user/{id}', 'UserCon ...
- GOF23设计模式之迭代器模式(iterator)
一.迭代器模式概述 提供一种可以遍历聚合对象的方式.又称为:游标(cursor)模式 结构: (1)聚合对象:存储数据 (2)迭代器:遍历数据 二.迭代器模式示例代码 定义:正向遍历迭代器和逆向遍历迭 ...
- Spring Cloud Bus 消息总线 RabbitMQ
Spring Cloud Bus将分布式系统中各节点通过轻量级消息代理连接起来. 从而实现例如广播状态改变(例如配置改变)或其他的管理指令. 目前唯一的实现是使用AMQP代理作为传输对象. Sprin ...