Spring boot - nháp
Question 01: What is Spring Boot?
Answer: Spring Boot is a Java framework that allows you to easily create stand-alone, production-grade Spring-based Java applications. It is often used in microservice architectures because of its simplicity. Applications created with Spring Boot can be executed with a simple
java -jar
command and also support traditional war deployment. Spring Boot supports the following embedded containers:Tomcat
Jetty
Undertow
Advantages:
Simplicity of deployment and execution allows for Dev/Prod parity, increasing product quality.
Provides features to fulfill non-functional requirements such as externalized configuration, security, metrics, and health checks.
Modules:
Spring Boot DevTools: Live-reload to speed up development.
Spring Boot Actuator: Monitoring and management of application.
Spring Boot Starters: Dependency set for technologies to minimize setup time.
Spring Boot Autoconfiguration: Configuration templates to minimize setup time.
Spring Boot also integrates with other Spring Framework technologies like Spring Web (MVC framework), template engines, Spring Security, Spring Data MongoDB, and many more.
Question 02: What are the advantages of using Spring Boot?
Answer:
Maximizes productivity.
Simplifies deployment by allowing the creation of executable jars and supporting traditional deployment on application servers.
Provides automatic configuration, reducing boilerplate configuration and allowing easy customization.
Enables Dev/Prod parity, ensuring consistency across environments.
Provides a set of managed dependencies.
Offers Maven plugins.
Provides non-functional features common for projects, such as externalized configuration, security, metrics, and health checks.
Integrates with microservice architecture tools for building highly available and fault-tolerant applications (Eureka, Ribbon, OpenFeign).
Integrates with systemd and init.d, allowing applications to run as Linux services.
Uses IoC/DI from the Spring Framework.
Question 03: Why is it "opinionated"?
Answer: Spring Boot is considered an "opinionated" framework because it comes with a general idea of how an application should be organized. It provides default configurations and module setups for technology-related aspects of the application (embedded databases, MVC view resolvers, template rendering engines, etc.).
Advantages:
Simplifies application setup.
Maximizes productivity by allowing you to focus on business code instead of setup.
Allows easy integration with technology modules (embedded databases, containers, etc.).
Minimizes setup code.
Disadvantages:
- If your application does not fall into the most common use cases supported by the framework, you will have to override many default setups, configurations, and project organizations, which might reduce productivity.
Question 04: What things affect what Spring Boot sets up?
Answer: Spring Boot uses autoconfiguration to detect dependencies on the classpath. Based on detected dependencies, Spring beans are configured to integrate with technologies like JPA, data sources, embedded databases, and template rendering engines.
Autoconfiguration Detection:
Spring Boot searches for
META-INF/spring.factories
on the classpath, which contains entries forEnableAutoConfiguration
listing all autoconfiguration classes.Autoconfiguration classes use
@ConditionalOn...
annotations to specify the conditions under which certain autoconfigurations should be applied.
Conditional Annotations:
@ConditionalOnBean
: Presence of a Spring Bean.@ConditionalOnMissingBean
: Absence of a Spring Bean.@ConditionalOnClass
: Presence of a class on the classpath.@ConditionalOnMissingClass
: Absence of a class on the classpath.@ConditionalOnCloudPlatform
: If a specified cloud platform is active.@ConditionalOnExpression
: If a SpEL expression is true.@ConditionalOnJava
: Presence of Java in a specified version.@ConditionalOnJndi
: If a JNDI location exists.@ConditionalOnWebApplication
: If a web application is present.@ConditionalOnNotWebApplication
: If it is not a web application.@ConditionalOnProperty
: Presence of a Spring property.@ConditionalOnResource
: Presence of a resource.@ConditionalOnSingleCandidate
: Only one candidate for the bean found.
Question 05: What is a Spring Boot starter POM? Why is it useful?
Answer: A Spring Starter POM is a Maven module that represents an empty jar with a set of dependencies required to work with a specified technology. Spring Starters may also provide autoconfiguration to create beans required to integrate the project with the intended technologies.
Usefulness:
Simplifies project setup by ensuring all dependencies and their correct versions are set.
If the Starter provides autoconfiguration, it integrates the technology with the Spring Framework.
Allows developers to focus on business code instead of spending time identifying and managing dependencies.
Question 06: Spring Boot supports both properties and YML files. Would you recognize and understand them if you saw them?
Answer: Spring Boot supports externalizing configuration using properties stored in properties files, which can be in YAML or Java Properties format. YAML is a superset of JSON and is convenient for specifying hierarchical data. Spring Boot supports YAML properties using the SnakeYAML library, included by default in
spring-boot-starter
.Example Transformation:
YAML:
app: name: spring-boot-app description: Example Spring Boot Application servers: - server1 - server2 - server3 environments: dev: name: Development Environment url: https://dev.example.com prod: name: Prod Environment url: https://prod.example.com
Java Property File:
app.name=spring-boot-app app.description=Example Spring Boot Application app.servers[0]=server1 app.servers[1]=server2 app.servers[2]=server3 app.environments['dev'].name=Development Environment app.environments['dev'].url=https://dev.example.com app.environments['prod'].name=Prod Environment app.environments['prod'].url=https://prod.example.com
Question 07: Can you control logging with Spring Boot? How?
Answer: Spring Boot allows you to configure various aspects of logging, including:
Logging Levels
Logging Patterns
Logging Colors
Logging Output (console, file)
Logging Rotation
Logging Groups
Logging System Used (Logback, log4j2, JDK)
Configuration Methods:
-
logging.level.root=WARN app.service.a.level=ALL app.service.b.level=FINEST app.service.c.level=FINER
Logging System Specific Configuration:
Logback:
<logger name="app.service.a" level="INFO"/> <logger name="app.service.b" level="DEBUG"/> <logger name="app.service.c" level="WARN"/>
Command Line Arguments:
$ java -jar myapp.jar --debug
debug=true trace=true
Logging Patterns:
-
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}) {blue} %clr(%-5p) %clr(${PID}){faint} %clr(---){faint} %clr([%8.15t]){cyan} %clr(%-40.40logger{0}){blue} %clr(:){red} %clr(%m){faint}%n
Logback:
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd} | %d{HH:mm:ss.SSS} | %thread | %5p | %logger{25} | %12(ID: %8mdc{id}) | %m%n</pattern> <charset>utf8</charset> </encoder> </appender>
Logging Colors:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
File Logging:
-
logging.file=myapp.log logging.path=/var/logs
Log Rotation:
-
logging.file.max-size=10MB logging.file.max-history=10
Logback:
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <fileNamePattern>${LOG_PATH}/archived/log_%d{dd-MM-yyyy}_%i.log</fileNamePattern> <maxFileSize>10MB</maxFileSize> <maxHistory>10</maxHistory> <totalSizeCap>100MB</totalSizeCap> </rollingPolicy>
Logging Groups:
logging.group.service-d-and-e=app.service.d, app.service.e
logging.level.service-d-and-e=DEBUG
Choosing Logging Subsystem:
Logback (default):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
log4j2:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
JDK (Java Util Logging):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency>
LogManager.getLogManager().readConfiguration(SpringBootConsoleApplication.class.getResourceAsStream("/logging.properties"));
Question 08: Where does Spring Boot look for property file by default?
Answer: Spring Boot looks for properties in the following locations:
Profile Specific:
Outside of Jar:
application-{profile}.properties
andapplication-{profile}.yml
in/config
subdirectory.application-{profile}.properties
andapplication-{profile}.yml
in the current directory.
Inside Jar:
application-{profile}.properties
andapplication-{profile}.yml
in/config
package on the classpath.application-{profile}.properties
andapplication-{profile}.yml
in the classpath root package.
Application Specific:
Outside of Jar:
application.properties
andapplication.yml
in/config
subdirectory.application.properties
andapplication.yml
in the current directory.
Inside Jar:
application.properties
andapplication.yml
in/config
package on the classpath.application.properties
andapplication.yml
in the classpath root package.
Changing Default Configuration File:
$ java -jar myproject.jar --spring.config.name=myproject
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties
Question 09: How do you define profile-specific property files?
Answer: Spring Boot allows defining profile-specific property files in two ways:
Dedicated Property File per Profile:
application-{profile}.properties
application-{profile}.yml
You can also use application-default.properties
or application-default.yml
to specify a property file used when no profile is set.
Multi-Profile YAML Document:
server:
url: https://local.service.com/
---
spring:
profiles: dev
server:
url: https://dev.service.com/
---
spring:
profiles: prod
server:
url: https://prod.service.com/
Question 10: How do you access the properties defined in the property files?
Answer: Spring Boot allows accessing properties defined in property files in the following ways:
@Value Annotation:
@Value("${PROPERTY_NAME}") private String propertyB;
@ConfigurationProperties(prefix = "app") @Getter @Setter public class AppConfiguration { private String propertyA; } @SpringBootApplication @EnableConfigurationProperties(AppConfiguration.class) public class SpringBootConsoleApplication implements CommandLineRunner { @Autowired private AppConfiguration appConfiguration; }
Environment Property Resolver:
@Autowired private Environment environment; environment.getProperty("app.propertyC");
Question 11: What properties do you have to define in order to configure external MySQL?
Answer: To configure external MySQL in Spring Boot, you need to specify the URL, username, and password for the data source by defining the following properties:
spring.datasource.url=jdbc:mysql://localhost:3306/spring-tutorial spring.datasource.username=spring-tutorial spring.datasource.password=spring-tutorial
Optionally, you can also explicitly specify the JDBC driver:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
To initialize the database during application startup via
data.sql
andschema.sql
, you also need to specify the property:spring.datasource.initialization-mode=always
Additionally, you need to specify the MySQL connector dependency:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
And a way to access the database, the simplest approach is to use JDBC:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency>
Question 12: How do you configure default schema and initial data?
Answer: Spring Boot uses the following scripts to configure the default schema and initial data:
schema.sql: Contains DDL for database objects creation.
data.sql: Contains data to be inserted upon database initialization.
Spring Boot will also load:
schema-${platform}.sql
data-${platform}.sql
The platform is the value of the spring.datasource.platform
property, allowing you to switch between database vendor-specific scripts (e.g., mysql, postgresql, oracle, etc.).
Spring Boot will automatically initialize only embedded databases. To initialize a regular database as well, you need to set the property:
spring.datasource.initialization-mode=always
If you would like to change the default script names, you can use:
spring.datasource.schema=custom-schema.sql
spring.datasource.data=custom-data.sql
Question 13: What is a fat jar? How is it different from the original jar?
Answer: A fat jar, also called an executable jar, contains the compiled code for your application and all its dependencies. Spring Boot uses a nested jars approach, meaning that the fat jar contains all dependencies as nested jars. This differs from the uber jar approach, which packs all dependencies into a single jar archive.
Differences:
Fat Jar: Contains nested jars for dependencies, making it easier to manage and see application dependencies. It includes a
MANIFEST.MF
file withMain-Class
andStart-Class
entries along withJarLauncher
code to execute the standalone jar.Original Jar: Does not contain all dependencies and is not executable by default.
To create a fat jar in your project, you need to use the spring-boot-maven-plugin
. Executing the application is as simple as running the command:
java -jar spring-boot-application-1.0-SNAPSHOT.jar
Question 14: What is the difference between an embedded container and a WAR?
Answer: WAR (Web Application Archive):
Represents a web module that cannot be executed in standalone mode.
Needs to be deployed to an application server like Tomcat or WildFly.
Can execute multiple applications simultaneously.
Embedded Container:
Used to execute executable jars.
Packed as a dependency in the executable jar.
Responsible for executing a single application.
WAR File Structure:
Assembly root/
├── JSP Pages, static HTML pages
├── META-INF/
│ └── MANIFEST.MF
├── WEB-INF/
│ └── web.xml (not required for Servlet 3+)
├── lib/
├── classes/
└── tags/
Spring Boot Executable JAR Structure:
Assembly root/
├── BOOT-INF/
│ ├── classes/
│ └── lib/
├── META-INF/
│ └── MANIFEST.MF
├── org.springframework.boot.loader/
│ └── JarLauncher.class
├── tomcat-embed-core-9.0.17.jar
└── ...
Creating a WAR file in Spring Boot:
Specify WAR packaging:
<packaging>war</packaging>
Specify required dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
Creating an Executable JAR with an Embedded Container in Spring Boot:
Specify required dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Use the Spring Boot Maven plugin:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin>
Question 15: What embedded containers does Spring Boot support?
Answer: Spring Boot supports the following embedded containers:
Tomcat: Default embedded container, automatically included when using
spring-boot-starter-web
.Jetty: To use Jetty, exclude
spring-boot-starter-tomcat
and includespring-boot-starter-jetty
.Undertow: To use Undertow, exclude
spring-boot-starter-tomcat
and includespring-boot-starter-undertow
.
Using Tomcat:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Using Jetty:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Using Undertow:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
Question 16: How does Spring Boot know what to configure?
Answer: Spring Boot knows what to configure by using auto-configuration classes defined in starter modules. Spring Boot searches for
META-INF/spring.factories
on the classpath. When it encounters the entryorg.springframework.boot.autoconfigure.EnableAutoConfiguration
, it loads the auto-configuration class specified by this property.Auto-Configuration Class:
A regular
@Configuration
class annotated with@ConditionalOn...
annotations specifying the conditions under which the class should be loaded.When conditions from
@ConditionalOn...
annotations are met, the@Configuration
class is loaded, providing beans that integrate your application with the specified technology.
Conditional Annotations Supported by Spring Boot:
@ConditionalOnBean
: Presence of a Spring Bean.@ConditionalOnMissingBean
: Absence of a Spring Bean.@ConditionalOnClass
: Presence of a class on the classpath.@ConditionalOnMissingClass
: Absence of a class on the classpath.@ConditionalOnCloudPlatform
: If a specified cloud platform is active (e.g., Cloud Foundry).@ConditionalOnExpression
: If a SpEL expression is true.@ConditionalOnJava
: Presence of Java in a specified version.@ConditionalOnJndi
: If a JNDI location exists.
: If a web application that uses
WebApplicationContextor
StandardServletEnvironment`.
@ConditionalOnNotWebApplication
: Application that is not a web application.@ConditionalOnProperty
: Presence of a Spring property.@ConditionalOnResource
: Presence of a resource.@ConditionalOnSingleCandidate
: Only one candidate for the bean found.
Question 17: What does @EnableAutoConfiguration do?
Answer: The
@EnableAutoConfiguration
annotation turns on auto-configuration of the Spring context. Auto-configuration tries to guess which Spring beans should be created for your application based on the configured dependencies and configurations with@ConditionalOn...
annotations.How It Works:
Spring searches for
META-INF/spring.factories
on the classpath. When it encounters the entryorg.springframework.boot.autoconfigure.EnableAutoConfiguration
, it loads the auto-configuration class specified by this property.When conditions specified in
@ConditionalOn...
annotations are met, beans pointed out by this configuration are created.
The @EnableAutoConfiguration
annotation should be applied to your application's @Configuration
class. When using Spring Boot with the @SpringBootApplication
annotation, @EnableAutoConfiguration
is not required because auto-configuration is turned on by default.
Question 18: What does @SpringBootApplication do?
Answer: The
@SpringBootApplication
annotation is used on the main application class for convenience. It is equivalent to using the following three annotations:@Configuration
: Allows additional bean registration.@EnableAutoConfiguration
: Enables context auto-configuration.@ComponentScan
: Turns on scanning for@Component
annotated classes.
Question 19: Does Spring Boot do component scanning? Where does it look by default?
Answer: Yes, Spring Boot performs component scanning because the
@SpringBootApplication
annotation enables component scanning with the use of the@ComponentScan
annotation.Default Behavior:
- Spring Boot searches for
@Component
annotated classes within the same root package as the@SpringBootApplication
annotated class.
- Spring Boot searches for
Customizing Component Scanning:
- You can change this behavior by adding additional packages to scan with the
scanBasePackages
or the type-safe versionscanBasePackageClasses
within the@SpringBootApplication
annotation.
Question 20: How are DataSource and JdbcTemplate auto-configured?
Answer: DataSource and JdbcTemplate are configured by Auto Configuration Classes defined in the
spring-boot-autoconfigure
module.DataSource is configured by
DataSourceAutoConfiguration
.JdbcTemplate is configured by
JdbcTemplateAutoConfiguration
.
Configuration Example:
Define properties for MySQL configuration:
spring.datasource.url=jdbc:mysql://localhost:3306/spring-tutorial spring.datasource.username=spring-tutorial spring.datasource.password=spring-tutorial
These properties will be injected into DataSourceProperties
by the prefix spring.datasource
and used by DataSourceAutoConfiguration
.
After having Auto Configuration enabled by default in Spring Boot, with the configured properties and the database connector on your classpath, you can use @Autowired
to inject DataSource
or JdbcTemplate
.
@Autowired
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
This allows you to easily configure and use DataSource and JdbcTemplate without additional boilerplate configuration.
Note: If you need to customize the auto-configuration, you can provide your own DataSource
bean, and Spring Boot will back off from its default configuration.
Question 21: What is spring.factories file for?
Answer: The
spring.factories
file, located in theMETA-INF/spring.factories
location on the classpath, is used by the Auto Configuration mechanism to locate Auto Configuration Classes. Each module that provides an Auto Configuration Class needs to have aMETA-INF/spring.factories
file with anorg.springframework.boot.autoconfigure.EnableAutoConfiguration
entry that points to the Auto Configuration Classes.The
META-INF/spring.factories
file is consumed by theSpringFactoriesLoader
class, which is used by theAutoConfigurationImportSelector
enabled by the@EnableAutoConfiguration
annotation used by default in the@SpringBootApplication
annotation.Each Auto Configuration Class lists conditions under which it should be applied, usually based on the existence of specific classes on the classpath or beans in the context. When conditions are met, the
@Configuration
class produces beans within the application context to integrate your application with the desired technology.Other uses of spring.factories:
Allows defining other entries to achieve context customization with classes like:
ApplicationContextInitializer
ApplicationListener
AutoConfigurationImportFilter
AutoConfigurationImportListener
BeanInfoFactory
ContextCustomizer
DefaultTestExecutionListenersPostProcessor
EnableAutoConfiguration
EnvironmentPostProcessor
FailureAnalysisReporter
FailureAnalyzer
ManagementContextConfiguration
PropertySourceLoader
ProxyDetector
RepositoryFactorySupport
SpringApplicationRunListener
SpringBootExceptionReporter
TemplateAvailabilityProvider
TestExecutionListener
【194†source】
Question 22: How do you customize Spring auto configuration?
Answer: You can customize Spring Auto Configuration by creating your own auto-configuration module with an Auto Configuration Class. To do that, you need to create a Java JAR module that contains the
META-INF/spring.factories
file with anorg.springframework.boot.autoconfigure.EnableAutoConfiguration
entry, which points to your Auto Configuration Class.The Auto Configuration Class is a class annotated with
@Configuration
, usually used together with@ConditionalOnClass
. Additionally, you can use@PropertySource
with@EnableConfigurationProperties
and@ConfigurationProperties
to introduce custom properties for your auto-configuration module.Inside the Auto Configuration Class, you should have
@Bean
annotated methods that will provide configured beans when@ConditionalOnClass
is met.
【186†source】
Question 23: What are the examples of @Conditional annotations? How are they used?
Answer: Spring Boot supports the following Conditional Annotations for Auto Configuration Classes:
@ConditionalOnBean
: Presence of a Spring Bean.@ConditionalOnMissingBean
: Absence of a Spring Bean.@ConditionalOnClass
: Presence of a class on the classpath.@ConditionalOnMissingClass
: Absence of a class on the classpath.@ConditionalOnCloudPlatform
: If a specified cloud platform is active (e.g., Cloud Foundry).@ConditionalOnExpression
: If a SpEL expression is true.@ConditionalOnJava
: Presence of Java in a specified version.@ConditionalOnJndi
: If a JNDI location exists.@ConditionalOnWebApplication
: If a web application that usesWebApplicationContext
orStandardServletEnvironment
.@ConditionalOnNotWebApplication
: Application that is not a web application.@ConditionalOnProperty
: Presence of a Spring property.@ConditionalOnResource
: Presence of a resource.@ConditionalOnSingleCandidate
: Only one candidate for the bean found.
@Conditional
annotations are used together with Auto Configuration Classes to indicate under which conditions a specific @Configuration
class should apply.
Example:
@Configuration
@ConditionalOnProperty(name = "file.store", havingValue = "network")
public class NetworkFileStoreAutoConfiguration {
@Bean
public FileStore networkFileStore() {
return new NetworkFileStore();
}
}
【192†source】
Question 24: What value does Spring Boot Actuator provide?
Answer: Spring Boot Actuator provides features that are required for your application to be viewed as a production-ready product, such as:
Monitoring
Health-checks
Metrics
Audit Events
The advantage of using Spring Boot Actuator is that you can use these features in your product without having to code them on your own. Enabling it is as simple as adding a dependency to your project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
After that, you can access endpoints available by default, such as:
/actuator/health
/actuator/info
【187†source】
Question 25: What are the two protocols you can use to access actuator endpoints?
Answer: Spring Boot Actuator supports two protocols:
HTTP: Endpoints can be accessed by any HTTP client, like CURL or a web browser. By default, the following are enabled:
/actuator/info
/actuator/health
JMX: Allows you to access Actuator MBeans under the
org.springframework.boot
group. You can access it with any tool that supports the JMX protocol, such as JConsole, which comes with the JDK.
Example:
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
【190†source】
Question 26: What are the actuator endpoints that are provided out of the box?
Answer: Spring Boot Actuator provides several out-of-the-box endpoints:
| ID | Description | Enabled by default | Default Exposure via JMX | Default Exposure via Web | | --- | --- | --- | --- | --- | | auditevents | Exposes audit events information for the current application. | Yes (with
AuditEventRepository
bean) | Yes | No | | beans | Displays a complete list of all the Spring beans in your application. | Yes | Yes | No | | caches | Exposes available caches. | Yes | Yes | No | | conditions | Shows the conditions that were evaluated on configuration and auto-configuration classes. | Yes | Yes | No | | configprops | Displays a collated list of all@ConfigurationProperties
. | Yes | Yes | No | | env | Exposes properties from Spring’sConfigurableEnvironment
. | Yes | Yes | No | | flyway | Shows any Flyway database migrations that have been applied. | Yes | Yes | No | | health | Shows application health information. | Yes | Yes | Yes | | httptrace | Displays HTTP trace information (default: last 100 HTTP request-response exchanges). | Yes (withHttpTraceRepository
bean) | Yes | No | | info | Displays arbitrary application info. | Yes | Yes | Yes | | integrationgraph | Shows the Spring Integration graph. | Yes | Yes | No | | loggers | Shows and modifies the configuration of loggers in the application. | Yes | Yes | No | | liquibase | Shows any Liquibase database migrations that have been applied. | Yes | Yes | No | | metrics | Shows metrics information for the current application. | Yes | Yes | No | | mappings | Displays a collated list of all@RequestMapping
paths. | Yes | Yes | No | | scheduledtasks | Displays the scheduled tasks in your application. | Yes | Yes | No | | sessions | Allows retrieval and deletion of user sessions from a Spring Session-backed session store. | Yes | Yes | No | | shutdown | Lets the application be gracefully shutdown. | No | Yes | No | | threaddump | Performs a thread dump. | Yes | Yes | No | | prometheus | Exposes metrics in a format that can be scraped by a Prometheus server. | No (only for Web Application) | N/A | No | | heapdump | Returns an hprof heap dump file. | No (only for Web Application) | N/A | No | | jolokia | Exposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux). | No (only for Web Application) | N/A | No | | logfile | Returns the contents of the logfile. | No (only for Web Application) | N/A | No |You can enable or disable Actuator Endpoints using properties:
management.endpoint.${ENDPOINT_NAME}.enabled=true management.endpoint.shutdown.enabled=true management.endpoint.beans.enabled=false management.endpoint.info.enabled=false management.endpoints.enabled-by-default=false
You can change endpoint exposure with properties:
management.endpoints.jmx.exposure.exclude management.endpoints.jmx.exposure.include management.endpoints.web.exposure.exclude management.endpoints.web.exposure.include management.endpoints.web.exposure.include=info, health, env, beans management.endpoints.web.exposure.include=*
Enable navigation through Actuator Endpoints by adding the HATEOAS dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency>
Visiting the main Actuator page:
http://localhost:8080/actuator
【195†source】
Question 27: What is info endpoint for? How do you supply data?
Answer: The Spring Boot Actuator
info
endpoint is used to provide arbitrary, non-sensitive, custom-defined data available at runtime that can provide additional information about the started application.Exposed via:
HTTP:
/actuator/info
JMX:
org.springframework.boot/Endpoint/Info
Common uses:
Application Name, Description, Version
Java Runtime Used
Git Information (e.g., Branch, Tag, Commit ID)
Supplying data:
Using property files, define
info.*
properties:info.app.name=Spring Boot Application info.app.description=This application exposes Spring Boot Actuator Endpoints info.app.version=1.0.0 info.java-vendor=${java.specification.vendor}
Implementing an
InfoContributor
bean:@Component public class SystemNameInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail("system-name", System.getProperty("os.name")); } }
【191†source】
Question 28: How do you change logging level of a package using loggers endpoint?
Answer: Spring Actuator allows you to list currently configured loggers with their levels in the following ways:
HTTP: By visiting
/actuator/loggers
endpoint.JMX: By executing
org.springframework.boot/Endpoint/Loggers/Operations/loggers
.
The loggers endpoint is exposed by default via JMX. To use it via HTTP, expose it by setting the following property in application.properties
:
management.endpoints.web.exposure.include=loggers
Viewing logging levels for an individual logger:
HTTP: Visit
/actuator/loggers/${LOGGER_NAME}
, for example,/actuator/loggers/
com.app
.question28
.JMX: Execute
org.springframework.boot/Endpoint/Loggers/Operations/loggerLevels
with the provided name parameter.
Changing logging level for a package:
HTTP: Via POST to
/actuator/loggers/${LOGGER_NAME}
:curl -i -X POST -H 'Content-Type: application/json' -d '{"configuredLevel": "TRACE"}' http://localhost:8080/actuator/loggers/com.app.question28
JMX: Via
org.springframework.boot/Endpoint/Loggers/Operations/configureLogLevel
withname
andconfiguredLevel
parameters set.
【193†source】
Question 29: How do you access an endpoint using a tag?
Answer: You access an endpoint using a tag by defining it as part of the request in the following way:
tag=KEY:VALUE
.Examples:
/actuator/metrics/http.server.requests?tag=status:200
/actuator/metrics/jvm.memory.max?tag=area:heap
You can also use multiple tags in one query with the usage of &
in the following way:
Examples:
/actuator/metrics/http.server.requests?tag=status:200&tag=method:GET
/actuator/metrics/jvm.memory.max?tag=area:heap&tag=id:G1%20Old%20Gen
Tags are used to filter the results of a query by one or multiple dimensions. They are often used with the metrics endpoint for data filtering.
【188†source】
Question 30: What is metrics for?
Answer: Spring Actuator provides the
metrics
endpoint, which can be used to examine metrics collected by the application during runtime.The
metrics
endpoint allows you to view information about specific metrics by visiting the metric-dedicated URI, for example,/actuator/metrics/process.cpu.usage
.You can drill down information further by using available tags, for example,
/actuator/metrics/jvm.memory.used?tag=area:heap
.The
metrics
endpoint allows you to view many out-of-the-box defined metrics:CPU Usage, CPU Core Count
Memory Usage, Max Memory Available
Threads Info
Garbage Collector Statistics
HTTP Requests Info
Embedded Tomcat Related Metrics
The metrics
endpoint is not exposed via Web by default. To make it available, add the following entry to application.properties
:
management.endpoints.web.exposure.include=metrics