Skillversitas

Configuration

application.properties vs application.yml

Spring Boot supports two configuration formats:

application.properties (default):

server.port=8081
server.servlet.context-path=/api
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

application.yml (more readable):

server:
  port: 8081
  servlet:
    context-path: /api
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb

You can use both at the same time, but if there's a conflict, application.properties takes precedence.

Changing the Port

# application.properties
server.port=9090

Now the application runs on http://localhost:9090 instead of 8080.

Context Path

server.servlet.context-path=/myservice

All endpoints must be prefixed with /myservice:

http://localhost:8080/myservice/hello

Profiles

Profiles allow different configuration per environment:

File Environment
application.properties Default (all environments)
application-dev.properties Development
application-prod.properties Production
application-test.properties Testing

Example of differing configuration:

# application-dev.properties
server.port=8081
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.show-sql=true

# application-prod.properties
server.port=443
spring.datasource.url=jdbc:mysql://prod-server:3306/mydb
spring.jpa.show-sql=false

Activate a profile at runtime:

mvn spring-boot:run -Dspring-boot.run.profiles=dev

Or in application.properties:

spring.profiles.active=dev

@Value Annotation

Read property values directly in Java:

@Component
public class MyAppConfig {

    @Value("${app.name}")
    private String appName;

    @Value("${app.version:1.0.0}")
    private String version; // default value: 1.0.0

    @Value("${server.port}")
    private int port;
}

@ConfigurationProperties

Cleaner for a group of properties:

# application.properties
app.name=SkillVersitas
app.description=Platform for learning to code
app.author=Luthfi
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private String name;
    private String description;
    private String author;
    // getters & setters
}
@Configuration
@EnableConfigurationProperties(AppProperties.class)
public class AppConfig {
}

Configuration Priority

Spring Boot has a priority order from highest to lowest:

  1. Command line arguments (--server.port=9090)
  2. System properties (-Dserver.port=9090)
  3. application-{profile}.properties
  4. application.properties
  5. Default values in code

Now you can configure the application to suit your needs. In the next chapter, we'll get to know Spring Boot Starters — dependency bundles that speed up development.