You are on page 1of 8

1.

Why do we need Spring Boot

2. What does @SpringBootApplication annotation signify and how is auto


configuration done?
@SpringBootApplication basically is a combination of @ComponentScan +
@EnableAutoConfiguration + @Configuration
when we add the spring-boot-starter-data-jpa dependency, we see that Spring Boot Auto-
configuration, auto-configures a datasource and an Entity Manager.

spring boot looks at a) frameworks available on the classpath b) existing configuration for the
application. based on these, spring boot provides basic configuration needed to configure the
application with these frameworks. this is called auto configuration .

3. What is @grab annotation in springboot


Standard Groovy codebase contains a @Grab annotation so that dependencies on third-party
libraries can be declared. Using @Grab annotation, Grape Dependency Manager downloads jar
in similar fashion as that of Maven/Gradle without any build tool.

4. spring-boot-properties-migrator
Helps project migrate from spring 1.x to 2
It will identify the properties that are no longer managed by Spring Boot.

5. Can you use spring-actuator to see logs ?


Yes you can
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Need to add a app.properties as well


management.endpoints.web.exposure.include=httptrace

6. Statelessness
Statelessness means that every HTTP request happens in complete isolation. When the
client makes an HTTP request, it includes all the information necessary for the server to
fulfill that request. The server never relies on information from previous requests. If that
information was important, the client would have to send it again in subsequent request.
Statelessness also brings new features. It’s easier to distribute a stateless application
across load-balanced servers. A stateless application is also easy to cache.

7. ORM in Spring
Spring-ORM is an umbrella module that covers many persistence technologies, namely
JPA, JDO, Hibernate and iBatis
8. JPA vs Hibernate
What is JPA?
A JPA (Java Persistence API) is a specification of Java which is used to access, manage,
and persist data between Java object and relational database. It is considered as a
standard approach for Object Relational Mapping.

JPA can be seen as a bridge between object-oriented domain models and relational
database systems. Being a specification, JPA doesn't perform any operation by
itself. Thus, it requires implementation. So, ORM tools like Hibernate, TopLink, and
iBatis implements JPA specifications for data persistence.

What is Hibernate?

A Hibernate is a Java framework which is used to store the Java objects in the relational
database system. It is an open-source, lightweight, ORM (Object Relational Mapping)
tool.

Hibernate is an implementation of JPA. So, it follows the common standards provided


by the JPA.

Need of JPA

As we have seen so far, JPA is a specification. It provides common prototype and


functionality to ORM tools. By implementing the same specification, all ORM tools (like
Hibernate, TopLink, iBatis) follows the common standards. In the future, if we want to
switch our application from one ORM tool to another, we can do it easily.

JPA Hibernate

Java Persistence API (JPA) defines the Hibernate is an Object-Relational Mapping


management of relational data in the Java (ORM) tool which is used to save the state of
applications. Java object into the database.

It is just a specification. Various ORM tools It is one of the most frequently used JPA
implement it for data persistence. implementation.

It is defined in javax.persistence package. It is defined in org.hibernate package.

The EntityManagerFactory interface is It uses SessionFactory interface to create


used to interact with the entity manager Session instances.
factory for the persistence unit. Thus, it
provides an entity manager.
It uses EntityManager interface to create, It uses Session interface to create, read, and
read, and delete operations for instances delete operations for instances of mapped
of mapped entity classes. This interface entity classes. It behaves as a runtime interface
interacts with the persistence context. between a Java application and Hibernate.

It uses Java Persistence Query It uses Hibernate Query Language (HQL) as


Language (JPQL) as an object-oriented an object-oriented query language to perform
query language to perform database database operations.
operations.

9. Circular Dependency Injection


If two beans are dependent on each other then we should not use Constructor injection in
both the bean definitions. Instead we have to use setter injection in any one of the beans.
(of course we can use setter injection n both the bean definitions, but constructor injections
in both throw 'BeanCurrentlyInCreationException'
If we use setter Injection, then you will not face any problem.
For constructor
Class A {
private final B b; // must initialize in ctor/instance block
public A(@Lazy B b)
{ this.b = b };
}
Class B {
private final A a; // must initialize in ctor/instance block
public B(A a) { this.a = a };
}

10. How to have global exception handling


Say we have a service class that gets the id or throws an exception

public Customer getCustomer(@PathVariable String id) {


return customerManager.getCustomer(id).orElseThrow(() -> new
NotFoundException("Customer not found with id " + id));}

To achieve this, we have to define global exception handler class with annotation
@RestControllerAdvice.
We have added one method "handleGenericNotFoundException", which handles exceptions
defined with
@ExceptionHandler(value = NotFoundException.class).
Any service generating exception "NotFoundException" will come to
“handleGenericNotFoundException” method, and the method will wrap the exception in
common format using the "CustomErrorResponse" class. In this case, the "customer not found"
error will be thrown as defined in “handleGenericNotFoundException” method inside the
ExceptionAdvice class.
@RestControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler(value = NotFoundException.class)
public ResponseEntity<CustomErrorResponse>
handleGenericNotFoundException(NotFoundException e) {
CustomErrorResponse error = new CustomErrorResponse("NOT_FOUND_ERROR",
e.getMessage());
error.setTimestamp(LocalDateTime.now());
error.setStatus((HttpStatus.NOT_FOUND.value()));
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}}

11. How to configure 2 data sources?


By default it is not possible in spring boot.’We should define and mark one of the DataSource
instances as @Primary, because various auto-configurations down the road expect to be able to
get one by type.

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first.configuration")
public HikariDataSource firstDataSource() {
return
firstDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.cla
ss).build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("app.datasource.second.configuration")
public BasicDataSource secondDataSource() {
return
secondDataSourceProperties().initializeDataSourceBuilder().type(BasicDataSource.cla
ss).build();
}

12. How to use configuration from Application.properties


Easiest way is @Value
@Value("${userBucket.path}")
private String userBucketPath;

Another way using Environment

@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
..... }

Application.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket

Use @Configuration
Employee.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {
private String name;
private String dept;
//Getters and Setters go here }

Now the properties value can be accessed by autowiring employeeProperties as follows.


@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept(); }

13. Why would you want to remove some auto configuration and how would you do
so?
If there are performance issues and you want to start up your spring boot application faster, you
can exclude certain auto configurations
@SpringBootApplication(exclude = {JacksonAutoConfiguration.class})
public class JustGifItApplication {

}
You need to be sure that you can exclude the auto configured dependency.

14. How do you exclude certain filters during auto configuration


@Bean
public FilterRegistrationBean
deRegisterHttpMethodFilter(HiddenHttpMethodFilter filter){
FilterRegistrationBean bean = new FilterRegistrationBean(filter);
bean.setEnabled(false);
return bean;
}
@Bean
public FilterRegistrationBean
deRegisterRequestContextFilter(RequestContextFilter filter){
FilterRegistrationBean bean = new FilterRegistrationBean(filter);
bean.setEnabled(false);
return bean;
}

15. What are the @ConditionalOn annotations such as @ConditionalOnClass,


@ConditionalOnMissingClass, @ConditionalOnBean,
@ConditionalOnMissingBean, @ConditionalOnProperty and what does it do in the
sense of autoconfiguration?
Basically if condition is met, then the configuration is added/excluded. Based on condition
interface as part of Spring4.
Match the configuration only in Presence or Absence of Class on Classpath.
Match the configuration only in Presence (@ConditionalOnBean) or
Abscene( @ConditionalOnMissingBean) of Bean
Presence or Absence of a Property (@ConditionalOnProperty)
There are many additional attributes to filter class/beans/properties.
There are additional conditions.. Like @ConditionalOnJava, OnResource etc.

16. YAML vs .properties file

YAML Properties
.yml extension .properties extension

Used in many languages Used mainly in java

Supports key/value pairs(Map), Lists and Supports key/value pairs, scalar types
Scalar Types

Hierarchical Non-hierarchical

Doesn’t work with @PropertySource Works with @PropertySource

Multiple Spring profiles in default config file One Spring profile per Config file

Format uses : Format uses =


a: a.x=1
X: 1 a.y=2
Y: 2

● What are stereotype annotations?


Spring Annotations are a form of metadata that provides data about a program. Annotations are
used to provide supplemental information about a program. It does not have a direct effect on
the operation of the code they annotate. It does not change the action of the compiled program.
@Component, @Repository @Service

● What is @Configuration used for?


If we have a bean to be defined, the overall class is defined as configuration so spring knows to
check it for a bean

@Configuration
public class CollegeConfig {
@Bean
public College collegeBean() {
return new College();
}
}
● Difference between @COmponent and @Bean
@Component - If any class is annotated with @Component it will be automatically detect by
using classpath scan.We can’t write specific implementation based on dynamic condition
@Bean - It is used to explicitly declare a single bean, rather than letting Spring do it
automatically. It works only when class is also annotated with @Configuration. We should use
@bean, if you want specific implementation based on dynamic condition.

● Compare @Configuration and @AutoConfiguration


Configuration is part of spring and is a way we moved away from XML Configuration
Autoconfiguration is
The @EnableAutoConfiguration annotation enables Spring Boot to auto-configure the
application context. Therefore, it automatically creates and registers beans based on both the
included jar files in the classpath and the beans defined by us.

● How is the factory pattern applied in Spring ?


Spring treats a bean container as a factory that produces beans

public interface BeanFactory {

getBean(Class<T> requiredType);
getBean(Class<T> requiredType, Object... args);
getBean(String name);

Each of the getBean methods is considered a factory method, which returns a bean matching
the criteria supplied to the method, like the bean's type and name.

Spring then extends BeanFactory with the ApplicationContext interface, which introduces
additional application configuration. Spring uses this configuration to start-up a bean container
based on some external configuration, such as an XML file or Java annotations.

● Compare @Controller and @RestController


@RestController is a type of Controller It was added to combine @Controller and
@ResponseBody

You might also like