0% found this document useful (0 votes)
355 views

Spring Framework Interview Preparation

Spring is an application framework that provides programming and configuration models for modern Java applications. Spring Boot is an extension of Spring that reduces configuration boilerplate. It includes embedded HTTP servers and auto-configuration capabilities. Some key Spring and Spring Boot components include Spring Core, Spring MVC, Spring Data JPA, and Spring Boot Starters which simplify dependency management.

Uploaded by

Sanju
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
355 views

Spring Framework Interview Preparation

Spring is an application framework that provides programming and configuration models for modern Java applications. Spring Boot is an extension of Spring that reduces configuration boilerplate. It includes embedded HTTP servers and auto-configuration capabilities. Some key Spring and Spring Boot components include Spring Core, Spring MVC, Spring Data JPA, and Spring Boot Starters which simplify dependency management.

Uploaded by

Sanju
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Spring Core

Spring Boot
Spring REST
Spring MVC
Spring JDBC
Spring AOP
Spring Boot Interview Prep
What is Spring?

Spring is an application Framework that provides a comprehensive programming and


configuration model for modern Java-based enterprise applications - on any kind of
deployment platform.

A key element of Spring is infrastructural support at the application level: Spring


focuses on the "plumbing" of enterprise applications so that teams can focus on
application-level business logic, without unnecessary ties to specific deployment
environments.

What is Spring Boot?


Spring Boot is an opinionated, convention-over-configuration focused addition to the
Spring platform – highly useful to get started with minimum effort and create stand-
alone, production-grade applications.
Spring vs. Spring Boot
Spring Framework eliminated the boilerplate code required for traditional Java
application.
For example, in the early days of Java web development, we needed to write a lot of boilerplate code to
insert a record into a data source. But by using the JDBCTemplate of the Spring JDBC module we can
reduce it to a few lines of code with only a few configurations.

Spring Boot is basically an extension of the Spring framework which eliminated the
boilerplate configurations required for setting up a Spring application.
What is the best Java IDE for Spring Framework?
Spring Tool Suite is an IDE to develop Spring applications. It is an Eclipse-based
development environment.
What is Spring Initializr?
Spring Initializr is a web-based tool (https://start.spring.io/). With the help of Spring
Initializr, we can easily generate the structure of the Spring Boot Project. The Initializr
offers a fast way to pull in all the dependencies you need for an application and does a
lot of the set up for you.

Spring Boot Starter


Dependency management is a critical aspects of any complex project. And doing this
manually is time consuming effort; the more time you spent on it the less time you have
on the other important aspects of the project.
Spring Boot starters were built to address Dependency management. Spring Boot
provides a number of “Starters” that let you add jars to your classpath.
Spring Boot Starters make the bootstrapping process much easier and faster. The starter
brings you required Maven dependencies as well as some predefined configuration bits.
example: The Web Starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Spring Boot Starter Parent
The spring-boot-starter-parent project is a special starter project – that provides default
configurations for our application and a complete dependency tree to quickly build
our Spring Boot project.
It also provides default configuration for Maven plugins such as maven-failsafe-
plugin, maven-jar-plugin, maven-surefire-plugin, maven-war-plugin.
Beyond that, it also inherits dependency management from spring-boot-
dependencies which is the parent to the spring-boot-starter-parent.
We can start using it in our project by adding this as a parent in our project's pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</parent>
We can always get the latest version of spring-boot-starter-parent from Maven
Central.
Once, we've declared the starter parent in our project, we can pull any dependency from
the parent by just declaring it in our dependencies tag.
Also, we don't need to define versions of the dependencies, Maven will download jar
files based on the version defined for starter parent in the parent tag.
For example, if we're building a web project, we can add spring-boot-starter-
web directly, and we don't need to specify the version:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

@SpringBootApplication
We use this annotation to mark the main class of a Spring Boot application:
@SpringBootApplication

class VehicleFactoryApplication {

public static void main(String[] args) {


SpringApplication.run(VehicleFactoryApplication.class, args);

@SpringBootApplication encapsulates @Configuration, @EnableAutoConfiguration


, and @ComponentScan annotations with their default attributes

Spring Bean Annotations


Spring bean annotations used to define different types of beans.
There're several ways to configure beans in a Spring container. We can declare them
using XML configuration.
We can declare beans using the @Bean annotation in a configuration class.
Or we can mark the class with one of the annotations from
the org.springframework.stereotype package and leave the rest to component
scanning.
Component Scanning
Spring can automatically scan a package for beans if component scanning is enabled.
@ComponentScan configures which packages to scan for classes with annotation
configuration. We can specify the base package names directly with one of
the basePackages or value arguments (value is an alias for basePackages):
@Configuration

@ComponentScan(basePackages = "com.baeldung.annotations")

class VehicleFactoryConfig {}

Also, we can point to classes in the base packages with


the basePackageClasses argument:
@Configuration

@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)

class VehicleFactoryConfig {}

Both arguments are arrays so that we can provide multiple packages for each.
If no argument is specified, the scanning happens from the same package where
the @ComponentScan annotated class is present.
@Component
@Component is a class level annotation. During the component scan, Spring
Framework automatically detects classes annotated with @Component.
For example:
@Component

class CarUtility {

// ...

By default, the bean instances of this class have the same name as the class name with
a lowercase initial. On top of that, we can specify a different name using the
optional value argument of this annotation.
Since @Repository, @Service, @Configuration, and @Controller are all meta-
annotations of @Component, they share the same bean naming behavior. Also, Spring
automatically picks them up during the component scanning process.

@Repository
DAO or Repository classes usually represent the database access layer in an
application, and should be annotated with @Repository:
@Repository

class VehicleRepository {

// ...

One advantage of using this annotation is that it has automatic persistence exception
translation enabled. When using a persistence framework such as Hibernate, native
exceptions thrown within classes annotated with @Repository will be automatically
translated into subclasses of Spring's DataAccessExeption.

@Service
The business logic of an application usually resides within the service layer – so we'll
use the @Service annotation to indicate that a class belongs to that layer:
@Service
public class VehicleService {

// ...

@Controller
@Controller is a class level annotation which tells the Spring Framework that this
class serves as a controller in Spring MVC:
@Controller

public class VehicleController {

// ...

@Configuration
Configuration classes can contain bean definition methods annotated with @Bean:
@Configuration

class VehicleFactoryConfig {

@Bean

Engine engine() {

return new Engine();

What Is an Actuator?
In essence, Actuator brings production-ready features to our application.
Monitoring our app, gathering metrics, understanding traffic, or the state of our
database becomes trivial with this dependency.
The main benefit of this library is that we can get production-grade tools without having
to actually implement these features ourselves.
Actuator is mainly used to expose operational information about the running
application – health, metrics, info, dump, env, etc. It uses HTTP endpoints or JMX
beans to enable us to interact with it.
Once this dependency is on the classpath several endpoints are available for us out of
the box. As with most Spring modules, we can easily configure or extend it in many
ways.

To enable Spring Boot Actuator we'll just need to add the spring-boot-
actuator dependency to our package manager. In Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Actuator comes with endpoints, the only two available by default


are /health and /info.
e.g. http://localhost:8080/health
Global Exception Handling: Using @ControllerAdvice Classes
A controller advice allows you to use exactly the same exception handling techniques
but apply them across the whole application, not just to an individual controller. You
can think of them as an annotation driven interceptor.
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({ EmployeeException.class })
protected ResponseEntity<Object> handleNotFound(
Exception ex, WebRequest request) {
return handleExceptionInternal(ex, "Employee not found",
new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}

Spring Boot CLI


The Spring Boot CLI is a command line tool that you can use if you want to quickly
develop a Spring application. It lets you run Groovy scripts. It is generally used for
doing quick prototype.
Essentials and Internals of Spring Boot Key Components:
Spring Boot gives us a great deal of magic to Spring application development. But
there are four core essentials or key components that it performs:
 Spring Boot Starters- We just tell Spring Boot what kind of functionality we
need; now it is responsibility of Spring Boot so that it will ensure that the libraries
needed are added to the build.
 Spring Boot AutoConfigurator- Spring Boot can automatically provide
configuration for application functionality common to many Spring applications.
 Spring Boot CLI- This optional feature of Spring Boot lets you write complete
applications with just application code, but no need for a traditional project build.
 Spring Boot Actuator- Gives us insight of application into what’s going on
inside of a running Spring Boot application.

How to access application.properties file values from your code


Example: suppose there are couple of properties provided for DB in application.properties file and I
want to get access of only group of DB properties in my code.

DB.url = “test”

DB.port=8990

DB.connection=myConnection

Solution is:

1. Create a class e.g. DBSettings and provide all the needed DB properties as fields and
corresponding getter/setter methods.
2. Annotate the class with @Configuration and @ConfigurationProperties(“DB”)

@Configuration
@ConfigurationProperties(“DB”)
public class DBSettings {
private int port;
private String url;
private String connection;

public int getPort() {


return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getConnection() {
return connection;
}
public void setConnection(String connection) {
this.connection = connection;
}
}

Logging in Spring Boot


When using starters, Logback is used for logging by default.
The default logging level of the Logger is preset to INFO, meaning
that TRACE and DEBUG messages are not visible.
In order to activate them without changing the configuration, we can pass the –
debug or –trace arguments on the command line:
Alternatively, if we're using Maven, we can define our log settings via the
command line:
mvn spring-boot:run
-Dspring-boot.run.arguments=--logging.level.org.springframework=TRACE

If we want to change the verbosity permanently, we can do so in


the application.properties file as described here:
logging.level.root=WARN

In order to use any logging library other than Logback, though, we need to
exclude it from our dependencies.
we need to turn it into a skinny version, and (only once) add our alternative library,
here through a starter itself:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>

Log Level: ERROR, WARN, INFO, DEBUG or TRACE


Spring Boot Interview
Questions
Q1. What Are the Differences Between Spring and Spring Boot?
The Spring framework provides comprehensive infrastructure support for
developing Java applications.
It's packed with some nice features like Dependency Injection and out of the box
modules like:

 Spring JDBC
 Spring MVC
 Spring Security
 Spring AOP
 Spring ORM
 Spring Test

These modules can drastically reduce the development time of an application.


Spring Framework eliminated the boilerplate code required for traditional Java
application.
For example, in the early days of Java web development, we needed to write a lot of
boilerplate code to insert a record into a data source. But by using
the JDBCTemplate of the Spring JDBC module we can reduce it to a few lines of code
with only a few configurations.

Spring Boot is basically an extension of the Spring framework which eliminated the
boilerplate configurations required for setting up a Spring application.
It takes an opinionated view of the Spring platform which paved the way for a
faster and more efficient development eco-system.
Here are just a few of the features in Spring Boot:

 Opinionated ‘starter' dependencies to simplify build and application


configuration
 Embedded server to avoid complexity in application deployment
 Metrics, Helth check, and externalized configuration
 Automatic config for Spring functionality – whenever possible

Let's get familiar with both of these framework step by step.

Q2. How Can We set up a Spring Boot Application With Maven?


We can include Spring Boot in a Maven project just like we would any other library.
However, the best way is to inherit from the spring-boot-starter-parent project and
declare dependencies to Spring Boot starters. Doing this lets our project reuse the
default settings of Spring Boot.
Inheriting the spring-boot-starter-parent project is straightforward – we only need to
specify a parent element in pom.xml:
<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.1.1.RELEASE</version>

</parent>

We can find the latest version of spring-boot-starter-parent on Maven Central.


Using the starter parent project is convenient, but not always feasible. For instance,
if our company requires all projects to inherit from a standard POM, we cannot rely on
the Spring Boot starter parent.
In this case, we can still get the benefits of dependency management with this POM
element:
<dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-dependencies</artifactId>

<version>2.1.1.RELEASE</version>

<type>pom</type>
<scope>import</scope>

</dependency>

</dependencies>

</dependencyManagement>

Finally, we can add some dependencies to Spring Boot starters, and then we're good
to go.
Q3. What Spring Boot Starters Are Available out There?
Dependency management is a crucial facet of any project. When a project is complex
enough, managing dependencies may turn into a nightmare, as there will be too many
artifacts involved.
This is where Spring Boot starters come in handy. Each starter plays a role as a one-
stop shop for all the Spring technologies we need. Other required dependencies are then
transitively pulled in and managed in a consistent way.
All starters are under the org.springframework.boot group, and their names start
with spring-boot-starter-. This naming pattern makes it easy to find starters,
especially when working with IDEs that support searching dependencies by name.
At the time of this writing, there are more than 50 starters at our disposal. The most
commonly used are:

 spring-boot-starter: core starter, including auto-configuration support, logging,


and YAML
 spring-boot-starter-aop: starter for aspect-oriented programming with Spring
AOP and AspectJ
 spring-boot-starter-data-jpa: starter for using Spring Data JPA with Hibernate
 spring-boot-starter-jdbc: starter for using JDBC with the HikariCP connection
pool
 spring-boot-starter-security: starter for using Spring Security
 spring-boot-starter-test: starter for testing Spring Boot applications
 spring-boot-starter-web: starter for building web, including RESTful,
applications using Spring MVC

For a complete list of starters, please see this repository.


To find more information about Spring Boot starters, take a look at Intro to Spring
Boot Starters.
Q4. How to Disable a Specific Auto-Configuration?
If we want to disable a specific auto-configuration, we can indicate it using
the exclude attribute of the @EnableAutoConfiguration annotation. For instance, this
code snippet neutralizes DataSourceAutoConfiguration:
// other annotations

@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)

public class MyConfiguration { }

If we enabled auto-configuration with the @SpringBootApplication annotation —


which has @EnableAutoConfiguration as a meta-annotation — we could disable auto-
configuration with an attribute of the same name:
// other annotations

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

public class MyConfiguration { }

We can also disable an auto-configuration with


the spring.autoconfigure.exclude environment property. This setting in
the application.properties file does the same thing as before:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.Data
SourceAutoConfiguration
Q5. How to Register a Custom Auto-Configuration?
To register an auto-configuration class, we must have its fully-qualified name listed
under the EnableAutoConfiguration key in the META-INF/spring.factories file:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baeldung.a
utoconfigure.CustomAutoConfiguration
If we build a project with Maven, that file should be placed in the resources/META-
INF directory, which will end up in the mentioned location during the package phase.
Q6. How to Tell an Auto-Configuration to Back Away When a Bean Exists?
To instruct an auto-configuration class to back off when a bean is already existent, we
can use the @ConditionalOnMissingBean annotation. The most noticeable attributes
of this annotation are:

 value: The types of beans to be checked


 name: The names of beans to be checked

When placed on a method adorned with @Bean, the target type defaults to the
method's return type:
@Configuration
public class CustomConfiguration {

@Bean

@ConditionalOnMissingBean

public CustomService service() { ... }

Q7. How to Deploy Spring Boot Web Applications as Jar and War Files?
Traditionally, we package a web application as a WAR file, then deploy it into an
external server. Doing this allows us to arrange multiple applications on the same
server. During the time that CPU and memory were scarce, this was a great way to
save resources.
However, things have changed. Computer hardware is fairly cheap now, and the
attention has turned to server configuration. A small mistake in configuring the server
during deployment may lead to catastrophic consequences.
Spring tackles this problem by providing a plugin, namely spring-boot-maven-
plugin, to package a web application as an executable JAR. To include this plugin,
just add a plugin element to pom.xml:
<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

With this plugin in place, we'll get a fat JAR after executing the package phase. This
JAR contains all the necessary dependencies, including an embedded server. Thus, we
no longer need to worry about configuring an external server.
We can then run the application just like we would an ordinary executable JAR.
Notice that the packaging element in the pom.xml file must be set to jar to build a
JAR file:
<packaging>jar</packaging>
If we don't include this element, it also defaults to jar.
In case we want to build a WAR file, change the packaging element to war:
<packaging>war</packaging>
And leave the container dependency off the packaged file:
<dependency>
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-tomcat</artifactId>

<scope>provided</scope>

</dependency>

After executing the Maven package phase, we'll have a deployable WAR file.
Q8. How to Use Spring Boot for Command Line Applications?
Just like any other Java program, a Spring Boot command line application must have
a main method. This method serves as an entry point, which invokes
the SpringApplication#run method to bootstrap the application:
@SpringBootApplication

public class MyApplication {

public static void main(String[] args) {

SpringApplication.run(MyApplication.class);

// other statements

The SpringApplication class then fires up a Spring container and auto-configures beans.
Notice we must pass a configuration class to the run method to work as the primary
configuration source. By convention, this argument is the entry class itself.
After calling the run method, we can execute other statements as in a regular program.
Q9. What Are Possible Sources of External Configuration?
Spring Boot provides support for external configuration, allowing us to run the same
application in various environments. We can use properties files, YAML files,
environment variables, system properties, and command-line option arguments to
specify configuration properties.
We can then gain access to those properties using the @Value annotation, a bound
object via the @ConfigurationProperties annotation, or the Environment abstraction.
Here are the most common sources of external configuration:

 Command-line properties: Command-line option arguments are program


arguments starting with a double hyphen, such as –server.port=8080. Spring
Boot converts all the arguments to properties and adds them to the set of
environment properties.
 Application properties: Application properties are those loaded from
the application.properties file or its YAML counterpart. By default, Spring Boot
searches for this file in the current directory, classpath root, or
their config subdirectory.
 Profile-specific properties: Profile-specific properties are loaded from
the application-{profile}.properties file or its YAML counterpart.
The {profile} placeholder refers to an active profile. These files are in the same
locations as, and take precedence over, non-specific property files.

Q10. What does it mean that Spring Boot supports relaxed binding?
Relaxed binding in Spring Boot is applicable to the type-safe binding of configuration
properties.
With relaxed binding, the key of an environment property doesn't need to be an exact
match of a property name. Such an environment property can be written in
camelCase, kebab-case, snake_case, or in uppercase with words separated by
underscores.
For example, if a property in a bean class with
the @ConfigurationProperties annotation is named myProp, it can be bound to any of
these environment properties: myProp, my-prop, my_prop, or MY_PROP.
Q11. What is Spring Boot Devtools Used For?
Spring Boot Developer Tools, or DevTools, is a set of tools making the development
process easier. To include these development-time features, we just need to add a
dependency to the pom.xml file:
<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

</dependency>

The spring-boot-devtools module is automatically disabled if the application runs in


production. The repackaging of archives also excludes this module by default. Hence,
it won't bring any overhead to our final product.
By default, DevTools applies properties suitable to a development environment. These
properties disable template caching, enable debug logging for the web group, and so
on. As a result, we have this sensible development-time configuration without setting
any properties.
Applications using DevTools restart whenever a file on the classpath changes. This is
a very helpful feature in development, as it gives quick feedback for modifications.
By default, static resources, including view templates, don't set off a restart. Instead, a
resource change triggers a browser refresh. Notice this can only happen if the
LiveReload extension is installed in the browser to interact with the embedded
LiveReload server that DevTools contains.
For further information on this topic, please see Overview of Spring Boot DevTools.
Q12. How to Write Integration Tests?
When running integration tests for a Spring application, we must have
an ApplicationContext.
To make our life easier, Spring Boot provides a special annotation for
testing – @SpringBootTest. This annotation creates an ApplicationContext from
configuration classes indicated by its classes attribute.
In case the classes attribute isn't set, Spring Boot searches for the primary
configuration class. The search starts from the package containing the test up until it
finds a class annotated with @SpringBootApplication or @SpringBootConfiguration.
Notice if we use JUnit 4, we must decorate the test class
with @RunWith(SpringRunner.class).
For detailed instructions, check out our tutorial on testing in Spring Boot.
Q13. What Is Spring Boot Actuator Used For?
Essentially, Actuator brings Spring Boot applications to life by enabling production-
ready features. These features allow us to monitor and manage applications when
they're running in production.
Integrating Spring Boot Actuator into a project is very simple. All we need to do is to
include the spring-boot-starter-actuator starter in the pom.xml file:
<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

Spring Boot Actuator can expose operational information using either HTTP or JMX
endpoints. Most applications go for HTTP, though, where the identity of an endpoint
and the /actuator prefix form a URL path.
Here are some of the most common built-in endpoints Actuator provides:

 auditevents: Exposes audit events information


 env: Exposes environment properties
 health: Shows application health information
 httptrace: Displays HTTP trace information
 info: Displays arbitrary application information
 metrics: Shows metrics information
 loggers: Shows and modifies the configuration of loggers in the application
 mappings: Displays a list of all @RequestMapping paths
 scheduledtasks: Displays the scheduled tasks in your application
 threaddump: Performs a thread dump

Differences between jar and war in Spring Boot?


Depends on your deployment. If you are planning to deploy your application to an existing
Java EE Application Server (e.g. JBoss), then standard approach is to perform a war build.

When you use fat jar approach, your application will be deployed on embedded application
container provided by spring boot. It is possible to build so called fat JAR that is
executable *.jar file with embedded application container (Tomcat as default option).

Building spring-boot application as *.war archive


The other option is to ship your application as old-fashioned war file. It could be deployed to
any servlet container out there. Here is step by step how-to list:
1. Change packaging to war (talking about maven's pom.xml)
2. Inherit main spring-boot application class from SpringBootServletInitializer and
override SpringApplicationBuilder configure(SpringApplicationBuilder) method
(see javadoc)
3. Make sure to set the scope of spring-boot-starter-tomcat as provided

What Are Profiles?


Every enterprise application has many environments, like:
Dev | Test | Stage | Prod | UAT / Pre-Prod

Each environment requires a setting that is specific to them. For example, in


DEV, we do not need to constantly check database consistency. Whereas in
TEST and STAGE, we need to. These environments host specific
configurations called Profiles.
How to configure different databases at runtime based on the specific
environment by their respective profiles.
Spring Boot — by default — provides just one property file
( application.properties). So, how will we segregate the properties based
on the environment?
The solution would be to create more property files and add the "profile"
name as the suffix and configure Spring Boot to pick the appropriate
properties based on the profile.
Then, we need to create three application.properties:

1. application-dev.properties
2. application-test.properties
3. application-prod.properties

Of course, the application.properties will remain as a master properties


file, but if we override any key in the profile-specific file, the latter will gain
precedence.
We will use the application.properties to use the key below:
spring.profiles.active=dev
Spring Core
What is Inversion of Control/Dependency Injection?
The smallest answer is: Inverting the control of injecting the
dependencies. The basic principle is that beans define their dependencies
(i.e. the other objects they work with) then, it is the job of the container to
actually inject those dependencies. This is fundamentally the inverse of the
bean instantiating or locating its dependencies hence the name Inversion of
Control.
What is Spring Framework?

The Spring Framework provides a comprehensive programming and


configuration model for modern Java-based enterprise applications - on any
kind of deployment platform.

A key element of Spring is infrastructural support at the application level:


Spring focuses on the "plumbing" of enterprise applications so that teams
can focus on application-level business logic, without unnecessary ties to
specific deployment environments.

What is the difference between BeanFactory and ApplicationContext?


The BeanFactory is the actual container which instantiates, configures, and
manages a number of beans. These beans typically collaborate with one
another, and thus have dependencies between themselves. These
dependencies are reflected in the configuration data used by the
BeanFactory.

ApplicationContext enhances BeanFactory functionality in a


more framework-oriented style. ApplicationContext has a couple of features
that distinguish it from the BeanFactory:

 Using the MessageSource - The ApplicationContext interface extends


an interface called MessageSource, and therefore provides messaging
(i18n or internationalization) functionality.
 Event propagation- Event handling in the ApplicationContext is
provided through the ApplicationEvent class
and ApplicationListener interface. If a bean which implements
the ApplicationListener interface is deployed into the context, every
time an ApplicationEvent gets published to the ApplicationContext,
that bean will be notified. Essentially, this is the
standard Observer design pattern. Example:

ContextClosedEvent - vent published when the


ApplicationContext is closed, using the close() method on the
ApplicationContext. Closed here means that singletons are
destroyed.

If I declare two Components/Beans with same name then what would happen?
Example:
@Component("EMP")
public class Employee {

. . .

@Component("EMP")
public class Manager {

. . .

Answer: It will cause build failure and will show the exception
ConflictingBeanDefinitionException

What is Dependency Injection?


Dependency injection is an approach to implement loose coupling among
the classes in an application.
Dependency: An object usually requires objects of other classes to
perform its operations. We call these objects dependencies.

Injection: The process of providing the required dependencies to an


object.

Thus dependency injection helps in implementing inversion of control (IoC).


This means that the responsibility of object creation and injecting the
dependencies is given to the framework (i.e. Spring) instead of the class
creating the dependency objects by itself.

We can implement dependency injection with:

 constructor-based injection
 setter-based injection
 field-based injection

Constructor Injection vs. Setter Injection


It is advisable to use constructor injection for all mandatory collaborators
and setter injection for all other properties.

Constructor Injection

In constructor-based injection, the dependencies required for the class


are provided as arguments to the constructor:
Before Spring 4.3, we had to add an @Autowired annotation to the
constructor. With newer versions, this is optional if the class has only
one constructor.

In the Cake class above, since we have only one constructor, we don’t
have to specify the @Autowired annotation. Consider the below
example with two constructors:
When we have a class with multiple constructors, we need to
explicitly add the @Autowired annotation to any one of the
constructors so that Spring knows which constructor to use to inject
the dependencies.

Setter Injection

In setter-based injection, we provide the required dependencies as


field parameters to the class and the values are set using the setter
methods of the properties. We have to annotate the setter method with
the @Autowired annotation.

The Cake class requires an object of type Topping. The Topping object
is provided as an argument in the setter method of that property:
Spring will find the @Autowired annotation and call the setter to inject
the dependency.

Field Injection

With field-based injection, Spring assigns the required dependencies


directly to the fields on annotating with @Autowired annotation.
In this type of Dependency Injection, Spring assigns the dependencies
directly to the fields. It is different than Constructor Injection or Setter
based Dependency Injection.

The interesting thing to understand is, Spring injects the dependencies,


even if the field is private. Spring uses Java Reflections to do so.
Hence it is called unsafe by many of the experts.
In this example, we let Spring inject the Topping dependency via field
injection:

Combining Field and Setter Injection

What will happen if we add @Autowired to both, a field and a setter?


Which method will Spring use to inject the dependency?
In the above example, we have added the @Autowired annotation to
both the setter and the field. In this case, Spring injects dependency
using the setter injection method.

Note that it’s bad practice to mix injection types on a single class as it
makes the code less readable.

Inject Bean By Name using @Resource

Spring supports Java SE Common Annotations (JSR-250). That


means, we can use @Resource instead of using the combination
of @Autowired and @Qualifier.
Why Should I Use Constructor Injection?

The advantages of using constructor injection:

All Required Dependencies Are Available at Initialization Time

We create an object by calling a constructor. If the constructor expects


all required dependencies as parameters, then we can be 100% sure
that the class will never be instantiated without its dependencies
injected.

The IoC container makes sure that all the arguments provided in
the constructor are available before passing them into the
constructor. This helps in preventing the
infamous NullPointerException.
Constructor injection is extremely useful since we do not have to write
separate business logic everywhere to check if all the required
dependencies are loaded, thus simplifying code complexity.
What About Optional Dependencies?

With setter injection, Spring allows us to specify optional dependencies by


adding @Autowired(required = false) to a setter method. This is not possible
with constructor injection since the required=false would be applied
to all constructor arguments.

We can still provide optional dependencies with constructor injection using


Java's Optional type.

Identifying Code Smells

Constructor injection helps us to identify if our bean is dependent on


too many other objects. If our constructor has a large number of
arguments this may be a sign that our class has too
many responsibilities. We may want to think about refactoring our
code to better address proper separation of concerns.

Preventing Errors in Tests

Constructor injection simplifies writing unit tests. The constructor


forces us to provide valid objects for all dependencies. Using mocking
libraries like Mockito, we can create mock objects that we can then
pass into the constructor.

We can also pass mocks via setters, of course, but if we add a new
dependency to a class, we may forget to call the setter in the test,
potentially causing a NullPointerException in the test.
Constructor injection ensures that our test cases are executed only
when all the dependencies are available. It’s not possible to have half
created objects in unit tests (or anywhere else for that matter).

Immutability

Constructor injection helps in creating immutable objects because a


constructor’s signature is the only possible way to create objects. Once
we create a bean, we cannot alter its dependencies anymore. With
setter injection, it’s possible to inject the dependency after creation,
thus leading to mutable objects which, among other things, may not be
thread-safe in a multi-threaded environment and are harder to debug
due to their mutability.

Conclusion

Constructor injection makes code more robust. It allows us to create


immutable objects, preventing NullPointerExceptions and other errors.

Circular dependencies
If you use predominantly constructor injection, it is possible to create an unresolvable circular
dependency scenario.

For example: Class A requires an instance of class B through constructor injection, and class B
requires an instance of class A through constructor injection. If you configure beans for classes A
and B to be injected into each other, the Spring IoC container detects this circular reference at
runtime, and throws a BeanCurrentlyInCreationException .

One possible solution is to edit the source code of some classes to be configured by setters rather
than constructors. Alternatively, avoid constructor injection and use setter injection only. In other
words, although it is not recommended, you can configure circular dependencies with setter
injection.
Spring @Required Annotation
The @Required annotation in spring is a method-level annotation applied to the setter
method of a bean property and thus making the setter-injection mandatory. This
annotation indicates that the required bean property must be injected with a value at the
configuration time. Below snippet shows how to use this annotation.

Activate @Required annotation


To activate this annotation in spring, developers will have to include
the <context:annotation-config /> tag in the configuration file. Below snippet shows how to
include this tag in the configuration file:
Difference between BeanFactory vs. ApplicationContext
We should use an ApplicationContext because an ApplicationContext includes all the
functionality of a BeanFactory , it is generally recommended over a plain BeanFactory , except
for scenarios where full control over bean processing is needed. Within
an ApplicationContext several kinds of beans are detected by convention that is, by bean
name or by bean type — in particular.

Feature BeanFactory ApplicationContext

The default implementation instantiates beans lazily eagerly when the application starts
when getBean() is
called

Annotation based dependency Not supported Yes supported

Integrated lifecycle management No Yes

Automatic BeanPostProcessor registration No Yes

Built-in ApplicationEvent publication No Yes


mechanism
Bean Life Cycle
Bean life cycle in Spring Bean Factory Container is as follows:

1. The Spring container instantiates the bean from the bean’s definition in
the XML file or Java.
2. Spring populates all of the properties using the dependency injection, as
specified in the bean definition.
3. If an init-method is specified for the bean, then it will be called.

If the Bean implements Bean aware interfaces i.e. BeanNameAware and


BeanFactoryAware then setBeanName() and setBeanFactory() method will be
called right after setting bean properties. The factory calls setBeanName() by
passing the bean’s ID and calls the setBeanFactory() by passing the instance
of itself.

If there are any BeanPostProcessors associated with the bean then


preProcessBeforeInitialization() method will be called before init() method
and postProcessAfterInitialization() methods will be called after init() method.

When container starts – a Spring bean needs to be instantiated, based on Java or XML
bean definition. It may also be required to perform some post-initialization steps to get it
into a usable state. Same bean life cycle is for spring boot applications as well.

After that, when the bean is no longer required, it will be removed from the IoC container.

Spring bean factory is responsible for managing the life cycle of beans created through
spring container.
Life cycle callbacks

Spring bean factory controls the creation and destruction of beans. To execute some
custom code, it provides the call back methods which can be categorized broadly in two
groups:

 Post-initialization call back methods


 Pre-destruction call back methods

Life cycle callback methods

Spring framework provides different ways for controlling life cycle events of a bean:

1. Implementing InitializingBean and DisposableBean callback interfaces

 Override afterPropertiesSet() method of InitializingBean


 Override destroy() method of DisposableBean

2. Custom init() and destroy() methods in bean configuration file

 <bean id=”xxx” init-method=”init” destroy-method=”destroy”/>

3. @PostConstruct and @PreDestroy annotations

Note: for Spring desktop (non-web) application we need to register


shutdown hook to the context for getting access lifecycle call back methods.
We should use
AbstractApplicationContext context =
ClasspathXmlapplicationcontect(“spring.xml”);
Context.registerShutdownHook();
When the destroy() method will call?
Call close() on the context, and you'll see the bean destroy-methods being called.
Singleton vs. Prototype Bean

Beans are defined to be deployed in one of two modes: singleton or non-singleton.


(The latter is also called a prototype).

When a bean is a singleton, only one shared instance of the bean will be managed and
all requests for beans with an id or ids matching that bean definition will result in that
one specific bean instance being returned.

The non-singleton, prototype mode of a bean deployment results in the creation of a


new bean instance every time a request for that specific bean is done.

Example:
<bean id="exampleBean"
class="examples.ExampleBean" singleton="false"/>
<bean name="yetAnotherExample"
class="examples.ExampleBeanTwo" singleton="true"/>
@Scope(value="prototype")
public class Alien {

. . .

Note: when deploying a bean in the prototype mode, the lifecycle of the bean changes
slightly. By definition, Spring cannot manage the complete lifecycle of a non-
singleton/prototype bean, since after it is created, it is given to the client and the
container does not keep track of it at all any longer. You can think of Spring's role when
talking about a non-singleton/prototype bean as a replacement for the 'new' operator.

How to inject a prototype-scoped bean into a singleton bean?


What is Lookup Method injection?
What is Method Injection?

Consider a singleton bean A which needs to use a non-singleton (prototype) bean B,


perhaps on each method invocation on A. The container will only create the singleton
bean A once, and thus only get the opportunity to set its properties once. There is no
opportunity for the container to provide bean A with a new instance of bean B every
time one is needed.
The solution is Lookup Method injection.
A method annotated with @Lookup tells Spring to return an instance of the
method's return type when we invoke it.
Essentially, Spring will override our annotated method and use our method's return
type as parameter of BeanFactory.getBean(param).
@Lookup is useful for

 Injecting a prototype-scoped bean into a singleton bean.


Spring lookup method injection is the process of dynamically overriding a
registered bean method.

The bean method should be annotated with @Lookup.

Spring returns the lookup result matched by the method's return type.

In above example the method getPrototypeBean is returning null. That


doesn't matter, because this method will actually be overridden by spring
dynamically. Spring uses CGLIB library to do so.

The dynamically generated code will look for the target bean in the
application context. Something like this:
Spring AOP
Concepts

Aspect-Oriented Programming (AOP) complements OOP by providing another way of


thinking about program structure. While OO decomposes applications into a hierarchy
of objects, AOP decomposes programs into aspects or concerns. This enables
modularization of concerns such as transaction management that would otherwise cut
across multiple objects. (Such concerns are often termed crosscutting concerns.)

One of the key components of Spring is the AOP framework. While the Spring IoC
containers (BeanFactory and ApplicationContext) do not depend on AOP, meaning you
don't need to use AOP if you don't want to, AOP complements Spring IoC to provide a
very capable middleware solution.

AOP is used in Spring:

 To provide declarative enterprise services, especially as a replacement for EJB


declarative services. The most important such service is declarative transaction
management, which builds on Spring's transaction abstraction.
 To allow users to implement custom aspects, complementing their use of OOP
with AOP.

AOP concepts

Let us begin by defining some central AOP concepts. These terms are not Spring-specific.
Unfortunately, AOP terminology is not particularly intuitive. However, it would be even more
confusing if Spring used its own terminology.

 Aspect: A modularization of a concern for which the implementation


might otherwise cut across multiple objects. Transaction management is a good
example of a crosscutting concern in J2EE applications. Aspects are
implemented using Spring as Advisors or interceptors.
 Joinpoint: Point during the execution of a program, such as a method
invocation or a particular exception being thrown. In Spring AOP, a joinpoint is
always method invocation.
 Advice: Action taken by the AOP framework at a particular joinpoint.
Different types of advice include "around," "before" and "throws" advice. Many
AOP frameworks, including Spring, model an advice as an interceptor,
maintaining a chain of interceptors "around" the joinpoint.
 Pointcut: Regular expressions (a set of joinpoints) specifying when an
advice should fire.
Spring JDBC
JDBCTemplate

This is the central class in the JDBC core package. It simplifies the use
of JDBC since it handles the creation and release of resources. This
helps to avoid common errors like forgetting to always close the
connection. It executes the core JDBC workflow like statement creation
and execution, leaving application code to provide SQL and extract
results. This class executes SQL queries, update statements or stored
procedure calls, imitating iteration over ResultSets and extraction of
returned parameter values. It also catches JDBC exceptions and
translates them to the generic, more informative, exception hierarchy
defined in the org.springframework.dao package.
Commonly used method:

execute(String sql)

Issue a single SQL execute, typically a DDL statement.

<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper)

Query given SQL to create a prepared statement from SQL and a list of arguments to
bind to the query, mapping each row to a result object via a RowMapper.

<T> List<T> query(String sql, RowMapper<T> rowMapper)

Execute a query given static SQL, mapping each row to a result object via a RowMapper.

<T> T queryForObject(String sql, RowMapper<T> rowMapper)

Execute a query given static SQL, mapping a single result row to a result object via a RowMapper.
<T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper)
Query given SQL to create a prepared statement from SQL and a list
of arguments to bind to the query, mapping a single result row
to a result object via a RowMapper.

int update(String sql)

Issue a single SQL update operation (such as an insert, update or delete statement).

DataSource

In order to work with data from a database, we need to obtain a connection to the
database. The way Spring does this is through a DataSource. A DataSource is part of the
JDBC specification and can be seen as a generalized connection factory. It allows a
container or a framework to hide connection pooling and transaction management
issues from the application code.

DriverManagerDataSource
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName( "org.hsqldb.jdbcDriver");
dataSource.setUrl( "jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername( "sa");
dataSource.setPassword( "");

BeanPropertyRowMapper
RowMapper implementation that converts a row into a new instance of the specified
mapped target class.
Constructor
BeanPropertyRowMapper(Class<T> mappedClass)

Create a new BeanPropertyRowMapper, accepting unpopulated properties in the target bean.


Sample DB insert code:

1. Query for Single Row

Spring BeanPropertyRowMapper, this class saves you a lot of time for the mapping.

import org.springframework.jdbc.core.BeanPropertyRowMapper;

public Customer findByCustomerId2(Long id) {

String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

return (Customer) jdbcTemplate.queryForObject(


sql,
new Object[]{id},
new BeanPropertyRowMapper(Customer.class));

Query for Multiple Rows


For multiple rows, we use jdbcTemplate.query()

public List<Customer> findAll() {

String sql = "SELECT * FROM CUSTOMER";

List<Customer> customers = jdbcTemplate.query(


sql,
new BeanPropertyRowMapper(Customer.class));

return customers;
}
Query for a Single Value

It’s same like query a single row from database,


uses jdbcTemplate.queryForObject()

3.1 Single column name

public String findCustomerNameById(Long id) {

String sql = "SELECT NAME FROM CUSTOMER WHERE ID = ?";

return jdbcTemplate.queryForObject(
sql, new Object[]{id}, String.class);

Count

public int count() {


String sql = "SELECT COUNT(*) FROM CUSTOMER";

return jdbcTemplate.queryForObject(sql, Integer.class);

How to call Stored Procedure

There are a number of ways to call stored procedures in Spring.


If you use CallableStatementCreator to declare parameters, you will be using
Java's standard interface of CallableStatement, i.e register out parameters
and set them separately.
Another way is SimpleJdbcCall.
Spring Exception Handling
You need not handle any database-related exceptions explicitly instead
Spring JDBC Framework will handle it for you. All the exceptions thrown by
the Spring JDBC Framework are subclasses of DataAccessException which is
a type of RuntimeException, so you need not handle it explicitly. Any
checked exception when thrown will be mapped to any of the subclasses of
the DataAccessException by the framework.
Don't handle any exceptions in the DAO layer, instead throw it to the front-
end and handle it. DataAccessException is a RuntimeException exception.
That allows us to handle non-recoverable persistence exceptions without
writing boilerplate catch-and-throw blocks and exception declarations in
DAOs.

The @Repository annotation


We are using @Repository annotation instead of @Component in our DAO
implementation. This annotation guarantees that all Spring DAO support,
including the exception translation is provided in a consistent way.
Spring Transaction

The code has an autowired JdbcTemplate , a handy template class that does all the
database interactions needed by the remaining code.

You also have a book method that can book multiple people. It loops through the list of
people and, for each person, inserts that person into the BOOKINGS table by using
the JdbcTemplate . This method is tagged with @Transactional , meaning that any
failure causes the entire operation to roll back to its previous state and to re-throw the
original exception. This means that none of the people are added to BOOKINGS if one
person fails to be added.
Statement,PreparedStatement and CallableStatement

JDBC Statement, CallableStatement, and PreparedStatement interfa


ces define the methods and properties that enable you to send SQL or PL/SQL commands and
receive data from your database. when the connection has been established to the database.

The Statement is used for executing a static SQL statement.

The PreparedStatement is used for executing a precompiled SQL statement.

The CallableStatement is an interface which is used to execute SQL stored procedures,


cursors, and Functions.
Spring MVC
The Spring Web model-view-controller (MVC) framework is designed
around a DispatcherServlet that dispatches requests to handlers, with
configurable handler mappings, view resolution, locale and theme resolution
as well as support for uploading files. The default handler is based on
the @Controller and @RequestMapping annotations, offering a wide range
of flexible handling methods.
DispatcherServlet is an expression of the “Front Controller” design pattern.
The request processing workflow in Spring Web MVC (high level)
The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base
class), and as such is declared in the web.xml of your web application. You
need to map requests that you want the DispatcherServlet to handle, by using a
URL mapping in the same web.xml file. This is standard Java EE Servlet
configuration; the following example shows such
a DispatcherServlet declaration and mapping:

<web-app>

<servlet>
<servlet-name>enrollment</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>golfing</servlet-name>
<url-pattern>/golfing/*</url-pattern>
</servlet-mapping>

</web-app>

With the above Servlet configuration in place, you will need to have a file
called /WEB-INF/ enrollment -servlet.xml in your application; this file will
contain all of your Spring Web MVC-specific components (beans).

The WebApplicationContext is an extension of the


plain ApplicationContext that has some extra features necessary for web
applications.
Controller
Controllers provide access to the application behavior that you typically define
through a service interface. Controllers interpret user input and transform it into
a model that is represented to the user by the view.

@Controller
public class HelloWorldController {

@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
}

The @Controller annotation indicates that a particular class serves the role of
a controller. Spring does not require you to extend any controller base class or
reference the Servlet API. However, you can still reference Servlet-specific
features if you need to.
The @Controller annotation acts as a stereotype for the annotated class,
indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations
To process the @PathVariable annotation, Spring MVC needs to find the
matching URI template variable by name. You can specify it in the annotation:

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model
model) {
// implementation omitted
}
Or if the URI template variable name matches the method argument name
you can omit that detail. As long as your code is not compiled without
debugging information, Spring MVC will match the method argument name to
the URI template variable name:

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
// implementation omitted
}

Handling Post request


@RequestMapping("/property" ,method=RequestMethod.POST)
@ResponseBody
public String property(@ModelAttribute("userDto") UserDto userDto ) {
System.out.println(userDto.getUsername());
System.out.println(userDto.getPassword());
return "Hello";
}

And your HTML / JSP:


<form method="post" name="userDto" action="http://localhost:8080/home/property">
<input name="username"/>
<input name="password"/>
<input type="submit"/>
</form>

You might also like