In a Spring Boot project, you can override default properties using various methods. Here are some common approaches:
-
application.properties or application.yml: Spring Boot allows you to define properties in a file named
application.properties
(orapplication.yml
) located in thesrc/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
-
Profile-specific properties: You can define properties specific to different profiles by creating separate configuration files with naming convention
application-{profile}.properties
orapplication-{profile}.yml
. Then, you can activate a profile using thespring.profiles.active
property in your mainapplication.properties
or through environment variables. For example:# application-dev.properties server.port=8081
-
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
-
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
-
Programmatic Configuration: You can also override properties programmatically by using Spring's
ConfigurableEnvironment
orEnvironment
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.