Spring Interview Module 4 Spring Boot Flashcards

1
Q

What is Spring Boot?

A

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 Architecture because of simplicity that it allows.

Applications created with Spring Boot can be executed with simple java –jar command and also allows traditional war deployment. Spring Boot supports following embedded containers:
 Tomcat
 Jetty
 Undertow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what advantages do spring boot have for simplicity of deployment and executions?

A

Simplicity of deployment and execution has many advantages, for example, it allows for Dev/Prod parity (https://12factor.net/) which increases product quality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what modules and features do spring boot provide?

A

Spring Boot provides number of features that can be used to fulfill non-functional requirements for the project (externalized configuration, security, metrics, health checks).

Spring Boot provides many modules under common umbrella:
 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 for technologies to minimize setup time e.g. jdbc template

On top of it, you can use all Spring Framework technologies, like:
 Spring Web – Spring MVC Framework
 Template Engines – server side rendering engines for web pages
 Spring Security – authentication and authorization framework
 Spring Data MongoDB – NoSQL database client
 … and many more

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  • What are the advantages of using Spring Boot?
A

 Maximizes productivity (dev only need to focus on the components required)
 Simplifies deployment, by allowing to create executable jar, and also supports traditional deployment on top of application server
 Provides automatic configuration which reduces boilerplate configuration, and allows easy customization when defaults are not sufficient (e.g. application.properties)
 Allows for Dev/Prod Parity
 Provides set of managed dependencies
 Provides Maven Plugins
 Provides non-functional features common for projects - externalized configuration, security, metrics, health checks
 Integrates with Micro Service Architecture Tools for building Highly Available and Fault Tolerant Applications – Eureka, Ribbon, OpenFeign
 Integrates with systemd and init.d, which allows to easily run applications as Linux Services
 Uses IoC/DI from Spring Framework

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why is spring boot “opinionated” and what are the advantages?

A

Spring Boot is “opinionated” framework because it comes with general idea on how application should be organized, provides default configurations and modules setups for technology related aspect of application. (embedded databases, mvc view resolvers, template rendering engines, …)

In comparison with Spring Framework, Spring Boot provides starters and autoconfigurations which intelligently fits default configuration based on defined dependencies. (e.g. spring boot autoconfigures data source when detect in-memory db dependency)

Main advantage on how Spring Boot approaches “opinionated” style, is that you can always override default configuration if it does not fit your use case.

“Opinionated” has following advantages:
 Simplifies application setup
 Maximizes productivity, by allowing you to focus on business code instead of setup of technology related code
 Allows you to write configuration only in case when defaults are not a good fit for your case
 Allows easy integration with technology modules (Embedded Databases, Containers …)
 Minimizes amount of setup code

The main disadvantage of “opinionated” framework is that, if your application does not fall into most use cases supported by framework, you will have to override most of default setup, configurations and project organization, which might harm your productivity

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a Spring Boot starter POM? Why is it
useful?

A

Spring Starter POM is a maven module that represents empty jar with set of dependencies required to work with specified technology. Spring Starter may also provide autoconfiguration to create beans required to integrate project with technologies that you intend to use.

Spring Starters are useful, because they simplify project setup by assuring that all dependencies in correct versions are set. If Starter provides autoconfiguration as well, it integrates technology with Spring Framework.

This allows you to focus on business code instead of having to spend time on identifying which dependency set is required and which versions are correct. Autoconfiguration allows you to use technology within Spring Framework without having to integrate technology with it manually.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what are the formats that Spring Boot allows you to externalize configuration?

A

 YAML
 Java Properties File

YAML is a superset of JSON and it is convenience for specifying hierarchical data.
Spring Boot supports YAML properties with usage of SnakeYAML library, which is included by default by spring-boot-starter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what are the aspects of logging can be controlled in spring boot?

A

 Logging Levels
 Logging Pattern
 Logging Colors
 Logging Output – console, file
 Logging Rotation
 Logging Groups
 Logging System used
- Logback – default
- log4j2
- JDK (Java Util Logging)
 Logging System specific configuration:
- Logback – logback-spring.xml
- log4j2 - log4j2-spring.xml
- JDK (Java Util Logging) - logging.properties

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

how to use spring boot to control logging levels?

A
  1. Logging Levels can be set via application.properties:
    logging.level.root=WARN
    app.service.a.level=ALL
  2. or by using logging system specific configuration, logback-spring.xml example:
    //< logger name=”app.service.a” level=”INFO”/>
    //< logger name=”app.service.b” level=”DEBUG”/>
  3. You can also use ––debug or ––trace argument when launching spring boot application:
    $ java -jar myapp.jar ––debug
  4. It is also possible to specify debug=true or trace=true in
    application.properties.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

how to use spring boot to control logging patterns?

A
  1. Logging patterns can be set via application.properties:
    logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS})
  2. or by using logging system specific configuration, logback-spring.xml example:
    < 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>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

where does spring boot default logs to? how to change the log output path?

A

Spring Boot by default logs only to console. You can change this behavior via application.properties or by using logging system specific configuration.

If you want to change this behavior via application.properties, you need to set one of following property:
 logging.file
 logging.path

You can also do this via logging system specific configuration, for example logbackspring.xml:
< root level=”INFO”>
< appender-ref ref=”CONSOLE”/>
< appender-ref ref=”FILE”/>
< appender-ref ref=”ROLLING-APPENDER”/>
< /root>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

how to use spring boot to control log rotation?

A

Spring Boot allows you to control logs rotation by specifying maximum file size and maximum number of logs file to keep in history.

To achieve this behavior through application.properties, you need to set following properties:
 logging.file.max-size
 logging.file.max-history

You can also configure logging system specific settings, for example in logbackspring.xml you can configure rolling appender:
< 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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

how to use spring boot to manage loggers by group?

A

Spring Boot can group loggers into group, which simplifies log management.

You can do this on application.properties level in following way:
logging.group.service-d-and-e=app.service.d, app.service.e
logging.level.service-d-and-e=DEBUG

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

how to control which logging subsystem to use in spring boot?

A
  1. To use default Logback, you just need to use spring-boot-starter
    dependency, autoconfiguration will setup all required beans
  2. To use log4j2, you just need to exclude spring-boot-starter-logging and add dependency to log4j2:
  3. To use JDK (Java Util Logging), you need to exclude spring-bootstarter-logging.
    Then initialize JDK logging in the code:
    LogManager.getLogManager().readConfiguration(
    SpringBootConsoleApplication.class.getResourceAsStream(“/logging.properties”)
    );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Where does Spring Boot look for property file
by default?

A

1. Profile Specific:
Outside of Jar:
application-{profile}.properties and application-{profile}.yml outside of jar in /config subdirectory
application-{profile}.properties and application-{profile}.yml outside of jar in current directory

Inside Jar:
application-{profile}.properties and application-{profile}.yml inside of jar in /config package on classpath
application-{profile}.properties and application-{profile}.yml inside of jar in classpath root package

2. Application Specific:
Outside of Jar:
application.properties and application.yml outside of jar in /config subdirectory
application.properties and application.yml outside of jar in current directory

Inside Jar:
application.properties and application.yml inside of jar in /config package on classpath
application.properties and application.yml inside of jar in classpath root package

You can change name of default configuration file with usage of
spring.config.name property:
$ java -jar myproject.jar –spring.config.name=myproject

You can also explicitly point location of configuration file with usage of
spring.config.location property:
$ java -jar myproject.jar –spring.config.location=classpath:/default.properties

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you define profile specific property
files in spring boot?

A

Spring Boot allows you to define profile specific property files in two ways:
1. Dedicated property file per profile:
 application-{profile}.properties
 application-{profile}.yml
 You can also use application-default.properties or application-default.yml filename to specify property file that should be used when no profile is set

2. Multi-profile YAML Document

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you access the properties defined in
the property files in spring boot?

A

1. @Value(“${PROPERTY_NAME}”)
You can inject properties into fields with usage of @Value annotation:
@Value(“${app.propertyB}”)
private String propertyB;

2. @ConfigurationProperties
You can define Data Object which will hold properties for defined prefix, you also need to register Configuration Properties Data Object with usage of EnableConfigurationProperties:
@ConfigurationProperties(prefix = “app”)
@Getter
@Setter
public class AppConfiguration {
private String propertyA;
}
@SpringBootApplication
@EnableConfigurationProperties(AppConfiguration.class)
public class SpringBootConsoleApplication implements CommandLineRunner{}

3. Environment Property Resolver
Inject and use Environment object.
@Autowired
private Environment environment;
environment.getProperty(“app.propertyC”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What properties do you have to define in order
to configure external MySQL in spring boot?

A
  1. To configure external MySQL in Spring Boot you need to specify URL, Username and Password for Data Source by defining following properties:
    spring.datasource.url=jdbc:mysql://localhost:3306/spring-tutorial
    spring.datasource.username=spring-tutorial
    spring.datasource.password=spring-tutorial
  2. Optionally, you can also explicitly specify JDBC Driver:
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  3. To initialize Database during application startup via data.sql and schema.sql you also need to specify property:
    spring.datasource.initialization-mode=always
  4. You also need to specify connector dependency:
    < artifactId>mysql-connector-java< /artifactId>
  5. You will also need a way to access database, simplest approach is to use JDBC:
    < artifactId>spring-boot-starter-data-jdbc< /artifactId>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you configure default schema and
initial data in spring boot?

A
  1. Spring Boot uses following scripts to configure default schema and initial data:
     schema.sql – contains DDL for db objects creation
     data.sql – contains data that should be inserted upon db initialization
  2. Spring Boot will also load:
     schema-${platform}.sql
     data-${platform}.sql
    platform is the value of spring.datasource.platform property, this allows you to switch between database vendor specific scripts, for example platform may be mysql,postgressql, oracle etc.
  3. Spring Boot will automatically initialize only embedded databases, if you want to initialize regular database as well, you need to set property spring.datasource.initialization-mode to always.
  4. If you would like to change default schema.sql and data.sql script names, you can use spring.datasource.schema and spring.datasource.data properties to achieve this.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is a fat jar? How is it different from the
original jar?

A

Fat jar, also called “executable jar”, is a jar that contains compiled code for your application and also all dependencies.
Spring Boot uses nested jars approach, that means that fat jar contains all dependencies as nested jars

 Original jar does not contain all dependencies
 Original jar is not executable by default

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between an embedded
container and a WAR?

A

WAR (Web Application Archive) is a file that represents web module. WAR cannot be executed in standalone mode, it needs to be deployed to Application Server like Tomcat or WildFly.

Embedded container is used to execute executables jars. Embedded container is packed as dependency in executable jar and will be responsible for executing only single application.
WAR approach on the other hand uses Application Server which might be used to execute multiple applications at the same time.

22
Q

What embedded containers does Spring Boot
support?

A

Spring Boot supports following embedded containers:
 Tomcat
 Jetty
 Undertow

Tomcat is used as default embedded container, it will be automatically included when
application is using spring-boot-starter-web:

To use Jetty Embedded Container, you need to exclude spring-boot-starter-tomcat and include spring-boot-starter-jetty:

To use Undertow Embedded Container, you need to exclude spring-boot-starter-tomcat and include spring-boot-starter-undertow:

23
Q

How does Spring Boot know what to configure?

A
  1. Spring Boot knows what to configure by usage of Auto Configuration Classes defined in starter modules.
    Spring Boot searches for META-INF/spring.factories on classpath, whenever entry org.springframework.boot.autoconfigure.EnableAutoConfiguration is encountered in this file, Auto Configuration Class pointed by this property is loaded.
  2. Auto Configuration class is a regular @Configuration class annotated with @ConditionalOn... annotation which specifies under which conditions @Configuration class should be loaded.
  3. When conditions from @ConditionalOn… annotation are matched, @Configuration class is loaded which provides beans that integrates your application with specified technology.
  4. Auto Configuration is often used with starter modules. Starter module provides set of dependencies, and optionally may provide Auto Configuration classes.
24
Q

What does @EnableAutoConfiguration do in Spring?

A

1.@EnableAutoConfiguration annotation turns on auto-configuration of Spring Context. Auto-configuration tries to guess Spring Beans that should be created for your application based on* configured dependencies* and configurations with @ConditionalOn… annotations.
2. When auto-configuration is turned on, Spring will search for META-INF/spring.factories on classpath, whenever entry
org.springframework.boot.autoconfigure.EnableAutoConfiguration is encountered in this file, Auto Configuration Class pointed by this property is loaded. When condition present in @ConditionalOn… annotation is matched, beans pointed out by this configuration are created.
3. @EnableAutoConfiguration annotation should be applied to your application @Configuration class, when using Spring Boot with @SpringBootApplication annotation, @EnableAutoConfiguration annotation is not required because auto-configuration is turned on by default.

25
Q

What does @SpringBootApplication do?

A

@SpringBootApplication annotation is supposed to be used on top of the class and it was introduced for convenience.

Usage of @SpringBootApplication annotation is equivalent to usage of following three annotations:
@Configuration – allows additional bean registration
@EnableAutoConfiguration – enables context auto-configuration
@ComponentScan – turns on scanning for @Component annotated classes

26
Q

Does Spring Boot do component scanning?
Where does it look by default?

A

Yes, Spring Boot is performing component scan, because
@SpringBootApplication annotation is enabling component scanning with usage of @ComponentScan annotation.

By default, Spring Boot will search for @Component annotated classes within the same root package as @SpringBootApplication annotated class.

You can change this behavior by adding additional packages to scan with scanBasePackages or type-safe version of it scanBasePackageClasses within @SpringBootApplication annotation.

27
Q

How are DataSource and JdbcTemplate autoconfigured?

A

DataSource and JdbcTemplate are configured by Auto Configuration Classes defined in spring-boot-autoconfigure module.

DataSource is configured by DataSourceAutoConfiguration, JdbcTemplate is configured by JdbcTemplateAutoConfiguration.
DataSourceAutoConfiguration requires some properties to be defined

example below shows MySQL configuration:
spring.datasource.url=jdbc:mysql://localhost:3306/spring-tutorial
spring.datasource.username=spring-tutorial
spring.datasource.password=spring-tutorial

Above 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, configured properties and Database Connector on your classpath, you can just use @Autowire to inject DataSource or JdbcTemplate.

28
Q

What is spring.factories file for in spring?

A

spring.factories file, located in META-INF/spring.factories location on the classpath, is used by Auto Configuration mechanism to locate Auto Configuration Classes.

Each module that provides Auto Configuration Class needs to have METAINF/spring.factories file with
org.springframework.boot.autoconfigure.EnableAutoConfiguration
entry that will point Auto Configuration Classes.

META-INF/spring.factories file is consumed by SpringFactoriesLoader class, which is used by AutoConfigurationImportSelector enabled by
@EnableAutoConfiguration annotation used by default in
@SpringBootApplication annotation.

Auto Configuration use case for spring.factories file is probably most popular one, it also allows you to define other entries and achieve context customization

29
Q

How do you customize Spring auto
configuration?

A
  • You can customize Spring Auto Configuration by creating your own autoconfiguration module with Auto Configuration Class.
  • To do that, you need to create java jar module which will contain METAINF/spring.factories file that contains
    org.springframework.boot.autoconfigure.EnableAutoConfiguration
    entry, which points to your Auto Configuration Class.
  • Auto Configuration Class is a class annotated with @Configuration annotation, usually used together with @ConditionalOnClass annotation.
  • Additionally you can use @PropertySource annotation with @EnableConfigurationProperties and @ConfigurationProperties
    annotations to introduce custom properties for your auto-configuration module.
  • Inside Auto Configuration Class you should have @Bean annotated methods, which will provide configured beans when @ConditionalOnClass is met.
30
Q

What are the examples of @Conditional
annotations? How are they used in spring boot?

A

@Conditional annotations are used together with Auto Configuration Classes, to indicate under which conditions, specific @Configuration class should apply.

Spring Boot supports following Conditional Annotations for Auto Configuration Classes:
*  ConditionalOnBean – presence of Spring Bean
*  ConditionalOnMissingBean – absence of Spring Bean
*  ConditionalOnClass – presence of class on classpath
*  ConditionalOnMissingClass – absence of class on classpath
*  ConditionalOnCloudPlatform – if specified cloud platform is active – for example Cloud Foundry
*  ConditionalOnExpression – if SpEL expression is true
*  ConditionalOnJava – presence of Java in specified version
*  ConditionalOnJndi – if JNDI location exists
*  ConditionalOnWebApplication – if a web application that uses
* WebApplicationContext or StandardServletEnvironment
*  ConditionalOnNotWebApplication – application that is not a web application
*  ConditionalOnProperty – presence of spring property
*  ConditionalOnResource – presence of resource
*  ConditionalOnSingleCandidate – only one candidate for the bean found

31
Q

What value does Spring Boot Actuator provide?

A

Spring Boot Actuator provides features, that are required for your application to be viewed as production ready product, such as:
 Monitoring
 Health-checks
 Metrics
 Audit Events

Advantage of using Spring Boot Actuator
- out of box solution. no coding required. just need dependency listing.

32
Q

What are the two protocols you can use to access spring actuator endpoints?

A

Spring Boot Actuator supports two protocols:
 HTTP
 JMX

HTTP endpoints can be accessed by any HTTP Client, like CURL or Web Browser, by default following are enabled:
 /actuator/info
 /actuator/health

33
Q

What are the spring boot actuator endpoints that are
provided out of the box?

A

default only expose health and info for web

You can enable or disable Actuator Endpoints with usage of property:
management.endpoint.${ENDPOINTNAME}.enabled=true

You can also disable ‘Enabled by default’ behavior with usage of property:
management.endpoints.enabled-by-default=false

You can change endpoints exposure with usage of properties:
~~~
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include
~~~

You can enable navigation through Actuator Endpoints, by usage of HATEOAS.
1. add dependency of HATEOAS to project
2. visiting main Actuator page:http://localhost:8080/actuator
3. navigate through returned links

34
Q

What is info endpoint for in spring boot actuator? How do you supply
data?

A

info endpoint is used to provide arbitrary, non-sensitive,
custom defined data, available at runtime that can provide additional information about started application.

exposed by default via protocols: HTTP and JMX

info endpoint is usually used to expose information like:
 Application Name, Description, Version
 Java Runtime Used
 Git Information – see git-commit-id-plugin

You can supply data to Spring Boot by defining info.* properties
~~~
info.app.name=Spring Boot Application
info.java-vendor = ${java.specification.vendor}
~~~

OR By implementing InfoContributor bean

35
Q

How do you change logging level of a package
using spring boot actuator loggers endpoint?

A

Spring Actuator allows you to list currently configured loggers by HTTP or JMX

loggers endpoint is exposed by default via JMX not HTTP

You can also view logging level for individual logger:
 via HTTP by visiting /actuator/loggers/${LOGGER_NAME}

via JMX by executing
org.springframework.boot/Endpoint/Loggers/Operations/loggerLevels

You can change logging level for package by:
 HTTP via POST to /actuator/loggers/${LOGGER_NAME} with payload ` ‘{“configuredLevel”: “TRACE”}’`

36
Q

How do you access a Spring Actuator endpoint using a tag?

A

You access an endpoint using a tag by defining it as part of the request in following way: tag=KEY:VALUE.
For example:
/actuator/metrics/http.server.requests?tag=status:200

Tag is used to filter results of query by one or multiple dimensions. It is often used with metrics endpoint for data filtering.

37
Q

What is spring boot actuator metrics for?

A

metrics endpoint can be used to examine metrics
collected by the application during runtime.

metrics endpoint allows you to view information about specific metric by visiting metric dedicated URI, for example /actuator/metrics/process.cpu.usage

metrics endpoint allows you to drill down information further by usage of available tags, for example /actuator/metrics/jvm.memory.used?tag=area:heap

metrics endpoint is not exposed via Web by default

38
Q

How do you create a custom spring actuator metric with or without tags?

A

Spring Boot Actuator allows you to create custom metrics with usage of MeterRegistry from Micrometer Application Metrics Facade.

Micrometer used by Spring Boot Actuator allows you to register Meter Primitives that will be exposed via /actuator/metrics endpoint

Registration of metric can be done via method inside MeterRegistry:
Counter objectsCount = meterRegistry.counter("storage.object.count", "type", "db");

or via usage of builder:
~~~
Counter objectsCount = Counter.builder(“storage.object.count”)
.tag(“type”, “db”).register(meterRegistry);
~~~

register simple meter without any dimensions:
Counter objectsCount = meterRegistry.counter("storage.object.count");

39
Q

What is spring actuator Health Indicator?

A

Health Indicator is a component used by /actuator/health endpoint to check if system is in a state which can be used to successfully handle requests.

/actuator/health endpoint is returning aggregated information on system status by evaluating all Health Indicators registered in HealthIndicatorRegistry.

can help monitor software and build a highly available architecture by load balancing to healthy instances only

To create custom Health Indicator, Spring Bean has to be created that implements HealthIndicator interface:

@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
return Health.up()
.withDetail("system-ready", true)
.build();
}
}
40
Q

What are the spring boot Health Indicator statuses that are
provided out of the box?

A

UP - component or subsystem is functioning as expected
DOWN - component or subsystem has suffered an unexpected failure
OUT_OF_SERVICE - component or subsystem has been taken out of service and should
not be used
UNKNOWN - component or subsystem is in an unknown state

spring provides default mapping of status to http response code
 UP -> HTTP 200
 UNKNOWN -> HTTP 200
 DOWN -> HTTP 503
 OUT_OF_SERVICE -> HTTP 503
You can change default mapping with usage of property for example:
management.health.status.http-mapping.DOWN=501

41
Q

How do you change the spring boot actuator Health Indicator status
severity order?

A

management.health.status.order=system-halted, DOWN, OUT_OF_SERVICE, UNKNOWN, UP

This property will be injected into HealthIndicatorProperties and used by OrderedHealthAggregator to resolve final status for application by aggregating statuses from all Health Indicators available in the system.

42
Q

Why do you want to leverage 3rd-party
external monitoring system for spring boot?

A

this way you can use monitoring functionalities without having to spend time coding them.

Spring Actuator uses Micrometer Application Metrics Facade which integrates with number of external monitoring systems. Provided dependency management and auto-configuration makes it easy to integrate Micrometer into your project.

Configuring external monitoring system is as easy as adding dependency:
~~~

<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-${monitoring-system-name}</artifactId>
</dependency>

~~~

43
Q

What are the Health Indicators that are
provided out of the box in spring boot actuator?

A

ApplicationHealthIndicator - Default Implementation, always up.
DiskSpaceHealthIndicator - Checks for low disk space.
DataSourceHealthIndicator - Checks the status of a DataSource and optionally runs a test query.
CassandraHealthIndicator - Checks that a Cassandra database is up.
CouchbaseHealthIndicator - Checks that a Couchbase cluster is up.
ElasticsearchHealthIndicator - Checks that an Elasticsearch cluster is up.
HazelcastHealthIndicator - Checks that a Hazelcast server is up.
InfluxDbHealthIndicator - Checks that an InfluxDB server is up.
JmsHealthIndicator - Checks that a JMS broker is up.
MailHealthIndicator - Checks that a mail server is up.
MongoHealthIndicator - Checks that a Mongo database is up.
RabbitHealthIndicator - Checks that a Rabbit server is up.
RedisHealthIndicator - Checks that a Redis server is up.
SolrHealthIndicator - Checks that a Solr server is up.
Neo4jHealthIndicator - Checks the status of a Neo4j by executing a Cypher.

Spring Actuator also provides Reactive Health Indicators for reactive applications, like those using Spring WebFlux

44
Q

What is the spring actuator Health Indicator status?

A

to inform Spring Actuator if system component checked by them is working correctly or not.

Each Health Indicator is expected to return status that represents guarded component state, status can be one of following:
 UP
 DOWN
 OUT_OF_SERVICE
 UNKNOWN
 Custom Defined

Spring Actuator is also using HealthAggregator, especially
OrderedHealthAggregator to aggregate statuses from all Health Indicators and decide on final status.

OrderedHealthAggregator is taking statuses from all
Health Indicators, sorts them by predefined order (DOWN, OUT_OF_SERVICE, UP, UNKNOWN), and takes first element after sorting, which represents highest priority status and becomes final status of the system.

45
Q

When do you want to use @SpringBootTest
annotation?

A

You should use @SpringBootTest annotation whenever writing JUnit Integration Test for product that is using Spring Boot.

Spring Boot approach to Integration Testing simplifies it by eliminating requirement of application deployment or establishing connection to other infrastructure.

@SpringBootTest annotation enables Spring Boot specific features on top of Spring Test that are useful for testing, like:
 Automated Context creation through SpringApplication class
 Web Environment for Testing – Mocked or Embedded
 Mocked Bean Injection via @MockBean annotation
 Spy Injection via @SpyBean annotation
 Ability to customize created context with @TestConfiguration annotated classes
 Auto configurations

46
Q

What does @SpringBootTest auto-configure?

A

@SpringBootTest annotation will auto-configure:
ApplicationContext for testing
 Test itself with tools used for testing

It is also possible to test only slice of the application with usage one of following:
@SpringBootTest#classes
@ContextConfiguration#classes
@AutoConfigure… annotations

@AutoConfigure… annotations allows you to configure specific environment and tools for testing, for example @AutoConfigureMockMvc will configure Mock Mvc
that can be used for Controllers testing.

Spring Boot Test includes annotations that are wrapping @AutoConfigure… annotations and make test development simpler:
 @JsonTest
 @WebMvcTest

47
Q

What dependencies does spring-boot-startertest brings to the classpath?

A

 JUnit - Unit Testing for Java Applications
 Spring Test - Spring Framework Support for Testing
 Spring Boot Test - Utilities and Integration Test Support for Spring Boot
 AssertJ - Fluent Assertion Library
 Hamcrest - Matchers Library
 Mockito - Mocking Framework
 JSONassert - JSON Assertion Library
 JsonPath - XPath for JSON
 XMLUnit - Tools for XML verification

48
Q

How do you perform integration testing with @SpringBootTest for a web application?

A

when writing Integration Test you should decide how many components should interact in the test for it to be meaningful. Components that are not meaningful can be omitted, or mocked with usage of @MockBean annotation.

Spring Boot allows you to write Integration Tests for Web Components in two ways:
 MockMvc

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CityControllerWebMockMvcTest {
@Autowired
private MockMvc mvc;
@Test
public void should...() throws Exception {
...
}
}

 Embedded Container
~~~
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CityControllerWebIntegrationTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void should…() {

}

~~~

49
Q

When do you want to use @WebMvcTest? What
does it auto-configure?

A

use @WebMvcTest annotation Integration Test that is focused on web layer of your application.

@WebMvcTest will create ApplicationContext that contains only web components and omits any other components.
Other components can be mocked with usage of @MockBean annotation or delivered by @Configuration annotated class imported.

@WebMvcTest supports two cases:
 Single Controller Auto-Configuration – annotate test by providing Controller class - @WebMvcTest(CityController.class)
 Multiple (All found) Controllers Auto-Configuration – just annotate test with @WebMvcTest

@WebMvcTest annotation will auto-configure:
 Mock Mvc
@Controller annotated class
@ControllerAdvice annotated class
@JsonComponent annotated class
@Converter annotated class
@GenericConverter annotated class
@Filter annotated class
@WebMvcConfigurer annotated class
@HandlerMethodArgumentResolver annotated class

50
Q

What are the differences between @MockBean
and @Mock?

A

@Mock annotation comes from Mockito Framework which allows for easy Mock creation.

@MockBean annotation comes from spring-boot-test, it creates Mockito Mock and also injects it into Application Context created by @SpringBootTest. All beans which refers to mocked class via @Autowired will get this mock injected instead of real class.

` @MockBean: creates mock and injects it into Application Context @Mock annotation:`
only creates it, if you want to inject it, you can do it manually or with @InjectMocks annotation, however injection is being done to the class not whole Application Context.

51
Q

When do you want use @DataJpaTest for? What
does it auto-configure?

A

Integration Test for JPA related components of application like Entities or Repositories.

@DataJpaTest annotation configures:
 In-memory embedded database – behavior can be disabled with
@AutoConfigureTestDatabase(replace = Replace.NONE)
 Scans and configures @Entity beans
 Scans and configures Spring Data Repositories
 Configures TestEntityManager
 Does not load other components like @Component, @Service, @Controller etc.

Every @DataJpaTest is transactional by default, after each test transaction is rolled back. You can use @Transactional annotation to customize this behavior.