Configuration
Configuration objects
You can use @ConfigurationProperties to bind Java objects to properties. If you define the prefix attribute, it defines the subtree of the properties for the mapping.
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private Database database;
private Service service;
public static class Database {
private String url;
}
public static class Service {
private String name;
}
}
app.database.url=localhost:3032
app.service.name=AService
Use dynamic ports in tests
Do not use static fix ports in your tests. Use SpringBootTest.WebEnvironment.RANDOM_PORT. Then you can access the port with the @LocalServerPort annotation
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {
@LocalServerPort
private int serverPort; // Contains the random server port
@Test
void test() {
Assertions.assertTrue(serverPort > 0);
}
}
Generic exception handling
If you put the annotation @ControllerAdvice on a class, it will work as a global class for handling exceptions. @RestController is similar but designed for RestController with response in JSON or XML.
@RestControllerAdvice
public class FileNotFoundHandler {
@ResponseStatus(HttpStatus.NO_CONTENT)
@ExceptionHandler(NoSuchElementException.class)
public void handleNotFoundError() {
}
}
Use dependency check plugin
Use the OWASP dependency check Maven plugin to scan your libraries for security issues.
Structured logs
Structured logging generates log output in a consistent, machine-readable format. There are several formats defined. e.g.
- ecs: Elastic Common Schema format
- logstash: Logstash format
To enable it. Add the following property to your application properties
logging:
structured:
format:
console: ecs
or for files
logging:
structured:
format:
file: ecs
file:
name: log.json