A. spring怎么加载非classpath路径下的properties配置文件
java"><beanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="locations">
<list>
<value>file:D:/workspace/test/conf/jdbc.properties</value>
</list>
</property>
</bean>
B. SpringBoot 如何优雅读取配置文件10分钟教你搞定
很多时候我们需要将一些常用的配置信息比如阿里云 oss 配置、发送短信的相关信息配置等等放到配置文件中。
下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。
application.yml 内容如下:
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!my-profile:name: Guide哥email: [email protected]:location: 湖北武汉加油中国加油books: -name: 天才基本法description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 -name: 时间的秩序description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 -name: 了不起的我description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?
1.通过 @value 读取比较简单的配置信息
使用 @Value("${property}") 读取比较简单的配置信息:
@Value("${wuhan2020}")String wuhan2020;
需要注意的是 @value这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。
2.通过@ConfigurationProperties读取并与 bean 绑定
LibraryProperties 类上加了 @Component 注解,我们可以像使用普通 bean 一样将其注入到类中使用。
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importjava.util.List;@Component@ConfigurationProperties(prefix ="library")@Setter@Getter@{privateString location;privateList books;@Setter@Getter@ToStringstaticclassBook{ String name; String description; }}
这个时候你就可以像使用普通 bean 一样,将其注入到类中使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/** *@authorshuang.kou */@ntsInitializingBean{privatefinalLibraryProperties library;(LibraryProperties library){this.library = library; }publicstaticvoidmain(String[] args){ SpringApplication.run(.class,args); }@(){ System.out.println(library.getLocation()); System.out.println(library.getBooks()); }}
控制台输出:
湖北武汉加油中国加油[LibraryProperties.Book(name=天才基本法, description........]
3.通过@ConfigurationProperties读取并校验
我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email 格式:
my-profile:name: Guide哥email: koushuangbwcx@
ProfileProperties 类没有加 @Component 注解。我们在我们要使用ProfileProperties 的地方使用@
EnableConfigurationProperties注册我们的配置 bean:
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importorg.springframework.validation.annotation.Validated;importjavax.validation.constraints.Email;importjavax.validation.constraints.NotEmpty;/***@authorshuang.kou*/@Getter@Setter@ToString@ConfigurationProperties("my-profile")@{@NotEmptyprivateString name;@Email@NotEmptyprivateString email;//配置文件中没有读取到的话就用默认值privateBooleanhandsome =Boolean.TRUE;}
具体使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;/** *@authorshuang.kou */@SpringBootApplication@EnableConfigurationProperties(ProfileProperties.class){privatefinalProfileProperties profileProperties;(ProfileProperties profileProperties){this.profileProperties = profileProperties; }publicstaticvoidmain(String[] args){ SpringApplication.run(.class,args); }@(){ System.out.println(profileProperties.toString()); }}
因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:
Binding to target org.springframework.boot.context.properties.bind.BindException:Failedtobindpropertiesunder'my-profile'to cn.javaguide.readconfigproperties.ProfileProperties failed:Property:my-profile.emailValue:koushuangbwcx@Origin:classpathresource[application.yml]:5:10Reason:mustbeawell-formedemailaddress
我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:
ProfileProperties(name=Guide哥, [email protected], handsome=true)
4.@PropertySource读取指定 properties 文件
importlombok.Getter;importlombok.Setter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;@Component@PropertySource("classpath:website.properties")@Getter@SetterclassWebSite{@Value("${url}")privateString url;}
使用:
@Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//https://javaguide.cn/
5.题外话:Spring 加载配置文件的优先级
Spring 读取配置文件也是有优先级的,直接上图:
原文链接:https://www.toutiao.com/a6791445278911103500/?log_from=7f5fb8f9b4b47_1640606437752
C. springboot加载自定义properties原理
springboot自定义属性文件通过value注解引入,和@autowired不同的是,它是由这个来处理,属性文件的读取和注入是在BeanDefinition级别,对象实例化之前。
我们建一个简单的类的梳理一下。
调用堆栈 从refresh开始,主要走了这几个方法:
invokes
->processConfigBeanDefinitions
ConfigurationClassParser->doProcessConfigurationClass
ConfigurationClassParser->processPropertySource
ConfigurationClassParser->addPropertySource
ConfigurationClassParser主要方法:
doProcessConfigurationClass->processPropertySource->addPropertySource
逻辑主要集中在doProcessConfigurationClass方法
doProcessConfigurationClass负责解析@PropertySource,@Import annotations,@ComponentScan等注解 。
1 调用processPropertySource处理自身的propertySource
2 扫描类上的ComponentScan,对扫出的类继续调用parse
3 处理@Import annotations等其他标签
processPropertySource结构很简单:
1根据注解里的location属性载入配置文件
2调用addPropertySource处理每个属性文件
addPropertySource这个类才是真正处理@value属性:
1把用户定义的properties文件加到Eniverment中去
2如果有相同name的属性文件,需要合并
CompositePropertySource 的场景其实是你有两个不同的文件,但是 @PropertySource中设置同样的name属性,这样CompositePropertySource 会做一个合并,按加入的时间顺序取。
增加一个proct2,PropertySource name都设置为myprod
debug到addPropertySource,newSource和existing已经不一样了。
environment的propertySources里也有两份文件了。
D. java web启动时修改并重新加载properties文件
大兄弟,我这儿有一个,你参考一下,但是输出流问题,没有得到解决。因为src在项目布置到tomcat上会消失的,所以你看看能不能解决?
E. 在java中如何读取properties文件
使用java.util.Properties
1、创建一个Properties对象。
2、使用对象的load方法加载你的property文件。
3、使用getProperty方法取值回。
例子:
package com.bill.test;
import java.io.FileInputStream;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws Exception{
答Properties property = new Properties();
property.load(new FileInputStream("你的文件位置"));
String value = property.getProperty("你的属性的key");
//TODO 使用value...
}
}
F. 如何在Spring容器中加载自定义的配置文件
自定义配置文件
配置文件名为:project.properties,内容如下:
[html] view plain
# 是否开启逻辑删除
project_del.filter.on=false
project_domain=
修改Spring配置文件
之前代码:
[html] view plain
<beanidbeanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertynamepropertyname="locations">
<list>
<value>classpath:dbinfo.properties</value>
</list>
</property>
</bean>
修改后的配置文件
[html] view plain
<beanidbeanid="propertyConfigurer"
class="com.hisun.core.util.">
<propertynamepropertyname="locations">
<list>
<value>classpath:dbinfo.properties</value>
<value>classpath:project.properties</value>
</list>
</property>
</bean>
加入了classpath:project.properties,其为自定义的配置文件
将PropertyPlaceholderConfigurer类修改为自定义类,
PropertyPlaceholderConfigurer类的具体作用可以查资料这块儿不做详细介绍
注意下:这个configurer类获取的是所有properties的属性map,如果希望处理某个properties文件,需要在properties中
做一个命名区别,然后在加载的时候,根据key的前缀,进行获取。
定义类
类的具体内容为下,
[java] view plain
importjava.util.HashMap;
importjava.util.Map;
importjava.util.Properties;
importorg.springframework.beans.BeansException;
importorg.springframework.beans.factory.config.;
importorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
publicclass {
privatestatic Map ctxPropertiesMap;
@Override
protectedvoid processProperties( beanFactoryToProcess,
Properties props)throws BeansException {
super.processProperties(beanFactoryToProcess, props);
ctxPropertiesMap =new HashMap();
for(Object key : props.keySet()) {
String keyStr = key.toString();
if(keyStr.startsWith("project_")){
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
}
publicstatic Object getContextProperty(String name) {
returnctxPropertiesMap.get(name);
}
}
定义获取配置文件中值的类SpringPropertiesUtil
类的具体内容如下:
[java] view plain
importorg.springframework.beans.BeansException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
importorg.springframework.stereotype.Component;
/**
* Spring-PropertiesUtil工具类 -获取属性值
*
*/
@Component
publicclass SpringPropertiesUtil {
publicstatic final String KEY = "propertyConfigurer";
privatestatic ApplicationContext applicationContext;
publicvoid setApplicationContext(ApplicationContext applicationContext)
throwsBeansException {
SpringPropertiesUtil.applicationContext = applicationContext;
}
publicstatic ApplicationContext getApplicationContext() {
returnapplicationContext;
}
/**
* 获取配置文件中的内容
*
* @param keyName
* @return
*/
publicstatic String parseStr(String keyName) {
cp = () applicationContext
.getBean(KEY);
returncp.getContextProperty(keyName).toString();
}
/**
* 获取配置文件中的内容
*
* @param keyName
* @return
*/
publicstatic int parseInt(String keyName) {
cp = () applicationContext
.getBean(KEY);
returnInteger.parseInt(cp.getContextProperty(keyName).toString());
}
/**
* 获取配置文件中的内容
*
* @param keyName
* @return
*/
publicstatic double parseDouble(String keyName) {
cp = () applicationContext
.getBean(KEY);
returnDouble.parseDouble(cp.getContextProperty(keyName).toString());
}
}
这样,在项目当中就能够方便快速的获取properties文件中配置的参数
如SpringPropertiesUtil.parseStr(“content”)