How can you override default properties in Spring boot Project?

ghz 9months ago ⋅ 99 views

In a Spring Boot project, you can override default properties using various methods. Here are some common approaches:

  1. application.properties or application.yml: Spring Boot allows you to define properties in a file named application.properties (or application.yml) located in the src/main/resources directory. You can override default properties by specifying them with the same key in this file. For example:

    # application.properties
    server.port=8081
    
  2. Profile-specific properties: You can define properties specific to different profiles by creating separate configuration files with naming convention application-{profile}.properties or application-{profile}.yml. Then, you can activate a profile using the spring.profiles.active property in your main application.properties or through environment variables. For example:

    # application-dev.properties
    server.port=8081
    
  3. Command-line arguments: You can pass properties directly as command-line arguments when running your Spring Boot application using the -D flag. For example:

    java -jar myapp.jar -Dserver.port=8081
    
  4. Environment variables: Spring Boot automatically converts environment variables to properties. You can override default properties by setting environment variables with the appropriate names. For example:

    export SERVER_PORT=8081
    
  5. Programmatic Configuration: You can also override properties programmatically by using Spring's ConfigurableEnvironment or Environment interfaces. This approach is more suitable for dynamic configuration based on runtime conditions.

    @SpringBootApplication
    public class MyAppApplication implements CommandLineRunner {
        @Autowired
        private ConfigurableEnvironment env;
    
        public static void main(String[] args) {
            SpringApplication.run(MyAppApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            // Override property programmatically
            env.getPropertySources().addFirst(new MapPropertySource("customProperties", Collections.singletonMap("server.port", "8081")));
        }
    }
    

These methods provide flexibility in overriding default properties in a Spring Boot application, allowing you to configure your application according to different environments or specific requirements. Choose the method that best suits your use case and preferences.