Setting the default active profile in Spring-boot

前端 未结 14 1914
感动是毒
感动是毒 2020-12-13 08:20

I want my default active profile to be production if -Dspring.profiles.active is not set.

I tried the following in my application.pro

14条回答
  •  青春惊慌失措
    2020-12-13 09:15

    One can have separate application properties files according to the environment, if Spring Boot application is being created. For example - properties file for dev environment, application-dev.properties:

    spring.hivedatasource.url=
    spring.hivedatasource.username=dev
    spring.hivedatasource.password=dev
    spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver
    

    application-test.properties:

    spring.hivedatasource.url=
    spring.hivedatasource.username=test
    spring.hivedatasource.password=test
    spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver
    

    And a primary application.properties file to select the profile:

    application.properties:

    spring.profiles.active=dev
    server.tomcat.max-threads = 10
    spring.application.name=sampleApp
    

    Define the DB Configuration as below:

    @Configuration
    @ConfigurationProperties(prefix="spring.hivedatasource")
    public class DBConfig {
    
        @Profile("dev")
        @Qualifier("hivedatasource")
        @Primary
        @Bean
        public DataSource devHiveDataSource() {
            System.out.println("DataSource bean created for Dev");
            return new BasicDataSource();
        }
    
        @Profile("test")
        @Qualifier("hivedatasource")
        @Primary
        @Bean
        public DataSource testHiveDataSource() {
            System.out.println("DataSource bean created for Test");
            return new BasicDataSource();
        }
    

    This will automatically create the BasicDataSource bean according to the active profile set in application.properties file. Run the Spring-boot application and test.

    Note that this will create an empty bean initially until getConnection() is called. Once the connection is available you can get the url, driver-class, etc. using that DataSource bean.

提交回复
热议问题