Springboot不使用默认的application.properties的两种方法


Springboot不使用默认的application.properties的两种方法

一、使用@PropertySource注解

@PropertySource("classpath:xxx.properties"),这个注解专门用来加载指定位置的properties文件,一般我们将自定义的配置文件放在resource目录下,编译后也就是位于classpath目录下。通用的情况是新建一个配置类,使用@Configuration标注,再加上之前的@PropertySource("classpath:xxx.properties")注解,而类的内部并不需要任何内容,这是一个纯粹的配置加载类。由于@Configuration的作用(底层@Component),他会被Spring的扫描器扫到,并加载到JVM,并创建Bean,而创建的时候就会执行配置文件中配置项的加载。这种方式加载的配置可以在任何Spring管辖的类中用@Value("${key}")的方式使用。

@Configuration
@PropertySource("classpath:business.properties")
public class MyConfig {
  
}

但是这种使用方式,应用多种开发环境不太适合。在开发的时候,我们最少分为开发环境、生产环境,更细还可分为预演环境、输出环境。因此可以使用application-dev.properties、application-prod.properties这样方便不同的配置之间的切换,因此这种方式不太适合。

二、修改spring.config.name

有两种方式,一种是纯粹抛弃application.properties,使用另外的配置名,在springboot启动类main方法中设置即可

@SpringBootApplication
public class ConsoleLauncher implements WebMvcConfigurer {
    public static void main(String[] args) {
        System.setProperty("spring.config.name", "business"); 
        SpringApplication.run(ConsoleLauncher.class, args);
    }
}

另外一种是,设置为两种并存的方法

@SpringBootApplication
public class ConsoleLauncher implements WebMvcConfigurer {
    public static void main(String[] args) {
        System.setProperty("spring.config.name", "application,business"); 
        SpringApplication.run(ConsoleLauncher.class, args);
    }
}

这样的话,在resource目录下,就会显示如下的情况。可以满足多种场合,多种需求,多种分类的配置需求。

image-20210227221143502


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM