Spring Interview Module 4 Spring Boot Flashcards
What is Spring Boot?
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
what advantages do spring boot have for simplicity of deployment and executions?
Simplicity of deployment and execution has many advantages, for example, it allows for Dev/Prod parity (https://12factor.net/) which increases product quality.
what modules and features do spring boot provide?
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
- What are the advantages of using Spring Boot?
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
Why is spring boot “opinionated” and what are the advantages?
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
What is a Spring Boot starter POM? Why is it
useful?
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.
what are the formats that Spring Boot allows you to externalize configuration?
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.
what are the aspects of logging can be controlled in spring boot?
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 to use spring boot to control logging levels?
- Logging Levels can be set via application.properties:
logging.level.root=WARN
app.service.a.level=ALL - 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”/> - You can also use ––debug or ––trace argument when launching spring boot application:
$ java -jar myapp.jar ––debug - It is also possible to specify debug=true or trace=true in
application.properties.
how to use spring boot to control logging patterns?
- Logging patterns can be set via application.properties:
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}) - 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>
where does spring boot default logs to? how to change the log output path?
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 to use spring boot to control log rotation?
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 to use spring boot to manage loggers by group?
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 to control which logging subsystem to use in spring boot?
- To use default Logback, you just need to use spring-boot-starter
dependency, autoconfiguration will setup all required beans - To use log4j2, you just need to exclude spring-boot-starter-logging and add dependency to log4j2:
- 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”)
);
Where does Spring Boot look for property file
by default?
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 do you define profile specific property
files in spring boot?
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 do you access the properties defined in
the property files in spring boot?
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”)
What properties do you have to define in order
to configure external MySQL in spring boot?
- 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 - Optionally, you can also explicitly specify JDBC Driver:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver - To initialize Database during application startup via data.sql and schema.sql you also need to specify property:
spring.datasource.initialization-mode=always - You also need to specify connector dependency:
< artifactId>mysql-connector-java< /artifactId> - You will also need a way to access database, simplest approach is to use JDBC:
< artifactId>spring-boot-starter-data-jdbc< /artifactId>
How do you configure default schema and
initial data in spring boot?
- 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 - 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. - 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.
- 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.
What is a fat jar? How is it different from the
original jar?
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