在日常开发过程中,发布一些产品或者框架时,会遇到某些功能需要一些配置才能正常运行,这时我们需要的提供默认配置项,同时用户也能覆盖进行个性化
创建initializer
public class framecontextinitializer implements applicationcontextinitializer { @override public void initialize(configurableapplicationcontext applicationcontext) { system.out.println("framecontextinitializer--start"); system.out.println("framecontextinitializer--end"); } }
配置initializer
resources/meta-inf文件夹下创建spring.factories文件,指定实现类
org.springframework.context.applicationcontextinitializer=com.haopan.frame.common.initializer.framecontextinitializer
实现initializer
读取默认yml文件
string frameyamlfilepath = classpathfileutil.getfilepathactual("systemfile/config/frame.yml"); public static string getfilepathactual(string classfilepath) { string filepath = ""; try { string templatefilepath = "tempfiles/classpathfile/"; file tempdir = new file(templatefilepath); if (!tempdir.exists()) { tempdir.mkdirs(); } string[] filepathlist = classfilepath.split("/"); string checkfilepath = "tempfiles/classpathfile"; for (string item : filepathlist) { checkfilepath += "/" + item; } file tempfile = new file(checkfilepath); if (tempfile.exists()) { tempfile.delete(); } //解析 classpathresource classpathresource = new classpathresource(classfilepath); inputstream inputstream = classpathresource.getinputstream(); checkfilepath = "tempfiles/classpathfile"; for (int i = 0; i < filepathlist.length; i++) { checkfilepath += "/" + filepathlist[i]; if (i == filepathlist.length - 1) { //文件 file file = new file(checkfilepath); if(!file.exists()){ fileutils.copyinputstreamtofile(inputstream, file); } } else { //目录 tempdir = new file(checkfilepath); if (!tempdir.exists()) { tempdir.mkdirs(); } } } inputstream.close(); filepath = checkfilepath; } catch (exception e) { e.printstacktrace(); } return filepath; }
将yml内容加到环境上下文
这边的addlast是执行顺序为最后读取,如果项目的yml文件没有读取到,则默认配置是一个保底
system.out.println("framecontextinitializer--start"); propertysource<?> propertysource = loader.load("frameconfiguration", new inputstreamresource(new fileinputstream(frameyamlfilepath))).get(0); applicationcontext.getenvironment().getpropertysources().addlast(propertysource); system.out.println("framecontextinitializer--end");
到此这篇关于springboot使用spring.factories加载默认配置的实现代码的文章就介绍到这了,更多相关springboot spring.factories加载配置内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论