spring boot自定义配置文件数据源

SpringBoot支持动态的读取文件,留下的扩展接口org.springframework.boot.env.EnvironmentPostProcessor。这个接口是spring包下的,使用这个进行配置文件的集中管理,而不需要每个项目都去配置配置文件。这种方法也是springboot框架留下的一个扩展(可以自己去扩展)

demo

/Users/naeshihiroshi/study/studySummarize/SpringBoot/(自己测试也可以随机在一个目录下建立一文件),目录下建立一个名为springboot.properties文件,

springboot.properties中定义一些配置,配置如下:

jdbc.root.user=zhihao.miaojdbc.root.password=242312321

定义MyEnvironmentPostProcessor实现EnvironmentPostProcessor接口

@Componentpublic class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {     @Override    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {        try{            InputStream inputStream = new FileInputStream("/Users/naeshihiroshi/study/studySummarize/SpringBoot/springboot.properties");            Properties properties = new Properties();            properties.load(inputStream);            PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("my",properties);            environment.getPropertySources().addLast(propertiesPropertySource);        }catch (IOException e){            e.printStackTrace();        }    }}

在classpath定义一个META-INF文件夹然后在其下面先建spring.factories文件,在其中指定:

image
org.springframework.boot.env.EnvironmentPostProcessor=com.zhihao.miao.processor.MyEnvironmentPostProcessor‘

启动类测试:

@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);        String username = context.getEnvironment().getProperty("jdbc.root.user");        String password = context.getEnvironment().getProperty("jdbc.root.password");        System.out.println("username==="+username);        System.out.println("password==="+password);        context.close();    }}

打印结果:

username===zhihao.miaopassword===242312321
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容