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

What is Spring Framework

The Spring Framework is a lightweight and integrated framework for developing Java enterprise applications, offering advantages like predefined templates, loose coupling through Dependency Injection, and support for web applications and RESTful services. It consists of various modules including Core Container, Data Access, Web, AOP, and Testing, each serving specific functionalities. Key concepts include Inversion of Control (IoC), Spring Beans, Dependency Injection, and various bean scopes, which enhance modularity, testability, and flexibility in application development.

Uploaded by

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

What is Spring Framework

The Spring Framework is a lightweight and integrated framework for developing Java enterprise applications, offering advantages like predefined templates, loose coupling through Dependency Injection, and support for web applications and RESTful services. It consists of various modules including Core Container, Data Access, Web, AOP, and Testing, each serving specific functionalities. Key concepts include Inversion of Control (IoC), Spring Beans, Dependency Injection, and various bean scopes, which enhance modularity, testability, and flexibility in application development.

Uploaded by

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

Spring Framework

1. What is Spring Framework?

It is a lightweight, loosely coupled and integrated framework for developing


enterprise applications in java.

2. Advantages of Spring Framework?

❖ Predefined Templates (Ex. Spring JDBC, JMS,..)


❖ It is Light weight. bcoz its implementation fully based on POJO and POJI
models.
❖ Loose coupling( by using Dependency Injection or Inversion of Control to write
components that are independent of each other)
❖ By using Spring MVC we can create web applications as well as restful web
services and we can return XML as well as JSON response

3. Why we should go for Spring framework than other frameworks?

1. Simplicity :

❖ Spring is Light weight. bcoz its implementation fully based on POJO and
POJI models. means it wont force a programmer to extend or
implement their class from any predefined class or interface given by
spring API.
❖ Struts is heavy weight. it will force the programmer to extend their
Action class.
❖ EJB is heavy weight. its tightly dependent with Application server.

2. Testability :

❖ While testing or debugging, if we want to change any code, no need to


restart the server to view the changes
❖ But in struts and EJB we must need to restart to view the changes
4. Spring framework modules?

1. Core Container

This container has the following four modules :

1. Spring Core: This module is the core of the Spring Framework. It provides
implementation for features like IoC (Inversion of Control) and Dependency
Injection with singleton design pattern.
2. Spring Bean: This module provides implementation for the factory design
pattern through BeanFactory.
3. Spring Context: This module is built on the solid base provided by the Core
and the Beans modules and is a medium to access any object defined and
configured.
4. Spring Expression Languages (SpEL): This module is an extension to
expression language supported by Java server pages. It provides a powerful
expression language for querying and manipulating an object graph, at
runtime.

2. Spring Data Access/ Integration

It consists of the following five modules:

1. JDBC: This module provides JDBC abstraction layer which eliminates the need
of repetitive and unnecessary exception handling overhead.
2. ORM: ORM stands for Object Relational Mapping. This module provides
consistency/ portability to our code regardless of data access technologies
based on object oriented mapping concept.
3. OXM: OXM stands for Object XML Mappers. It is used to convert the objects
into XML format and vice versa. The Spring OXM provides an uniform API to
access any of these OXM frameworks.
4. JMS: JMS stands for Java Messaging Service. This module contains features for
producing and consuming messages among various clients.
5. Transaction: This module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your
POJOs. All the enterprise level transaction implementation concepts can be
implemented in Spring by using this module.
3. Spring Web

Web layer includes the following modules:

1. Web: This module using servlet listeners and a web-oriented application


context, provides basic web-oriented integration features like multi-part file
upload functionality and the initialization of the IoC container.
2. Web-Servlet: This module contains Model-View-Controller (MVC) based
implementation for web applications. It provides all other features of MVC,
including UI tags and data validations.
3. Web-Socket: This module provides support for WebSocket based and two-way
communication between the client and the server in web applications.
4. Web-Portlet: This module is also known as Spring-MVC-Portlet module. It
provides the support for Spring based Portlets and mirrors the functionality of
a Web-Servlet module.

4. Aspect Oriented Programming (AOP)

AOP language is a powerful tool which allows developers to add enterprise


functionality to the application such as transaction, security etc. It allows us to
write less code and separate the code logic. AOP uses cross-cutting concerns.

5. Instrumentation

This module provides class instrumentation support and class loader


implementations that are used in certain application servers.

6. Test

This module supports the testing of Spring components with JUnit or TestNG. It
provides consistent loading of Spring ApplicationContexts and caching of
those contexts. It also provides mock objects that we can use to test our code
in isolation.
5. What is Inversion of control(IOC)?

❖ It is the core container of Spring.


❖ The IoC container receives beans information from either an XML file, Java
annotations, or Java code
❖ Based on the configuration, This Container will create the objects, configures and
manages the beans entire life cycle.
❖ These created objects through this process called Spring Beans. These objects are
ready to Inject by Dependency Injection (DI).

6. What is Spring bean?

Spring Bean is nothing special, any object in the Spring framework that we initialize
through Spring container is called Spring Bean. Any normal Java POJO class can be a
Spring Bean if it’s configured to be initialized via container by providing configuration
metadata information.

6. IOC types?

two types of containers, these are

BeanFactory

● Bean Factory provides the basic support for Dependency Injection.


● BeanFactory follows lazy-initialization technique which means beans
are loaded when getBean() method is called.

ApplicationContext

● It is the advanced Spring container and is built on top of the


BeanFactory interface.
● ApplicationContext supports the features supported by Bean Factory
but also provides some additional functionalities like
Internationalization, Event Handling, supports AOP and Annotation
based web application.
● ApplicationContext follows eager-initialization technique which
means instance of beans are created as soon as you create the
instance of Application context.

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext(AppConfig.class);

AccountService service1 = context.getBean("accountService",


AccountService.class);

7. Which one is recommended either Beanfactory or application context?

The ApplicationContext container includes all functionality of the


BeanFactorycontainer, so it is generally recommended over BeanFactory.
BeanFactory can still be used for lightweight applications like mobile devices or
applet-based applications where data volume and speed is significant.

8. Spring Bean Life Cycle Diagram and Steps


Find the spring bean life cycle diagram. Here are showing the steps involved in spring
bean life cycle.
A bean life cycle includes the following steps.
1. Within IoC container, a spring bean is created using class constructor.
2. Now the dependency injection is performed using setter method.
3. Once the dependency injection is completed, BeanNameAware.setBeanName() is called. It
sets the name of bean in the bean factory that created this bean.
4. Now < code>BeanClassLoaderAware.setBeanClassLoader() is called that supplies the
bean class loader to a bean instance.
5. Now < code>BeanFactoryAware.setBeanFactory() is called that provides the owning
factory to a bean instance.
6. Now the IoC container calls BeanPostProcessor.postProcessBeforeInitialization on the
bean. Using this method a wrapper can be applied on original bean.
7. Now the method annotated with @PostConstruct is called.
8. After @PostConstruct, the method InitializingBean.afterPropertiesSet() is called.
9. Now the method specified by init-method attribute of bean in XML configuration is called.
10. And then BeanPostProcessor.postProcessAfterInitialization() is called. It can also be used
to apply wrapper on original bean.
11. Now the bean instance is ready to be used. Perform the task using the bean.
12. Now when the ApplicationContext shuts down such as by using registerShutdownHook()
then the method annotated with @PreDestroy is called.
13. After that DisposableBean.destroy() method is called on the bean.
14. Now the method specified by destroy-method attribute of bean in XML configuration is
called.
15. Before garbage collection, finalize() method of Object is called.

Initialization Callbacks
In the bean life cycle initialization callbacks are those methods which are called just after the
properties of the bean has been set by IoC container. The spring InitializingBean has a
method as afterPropertiesSet() which performs initialization work after the bean properties
has been set. Using InitializingBean is not being recommended by spring because it couples
the code. We should use @PostConstruct or method specified by bean attribute init-method
in XML which is the same as initMethod attribute of @Bean annotation in JavaConfig. If all
the three are used together, they will be called in below order in bean life cycle.
1. First @PostConstruct will be called.
2. Then InitializingBean.afterPropertiesSet() is called
3. And then method specified by bean init-method in XML or initMethod of @Bean in
JavaConfig.

Destruction Callbacks
In bean life cycle when a bean is destroyed from the IoC container, destruction callback is
called. To get the destruction callback, bean should implement spring DisposableBean
interface and the method destroy() will be called. Spring recommends not to use
DisposableBean because it couples the code. As destruction callback we should use
@PreDestroy annotation or bean attribute destroy-method in XML configuration which is
same as destroyMethod attribute of @Bean in JavaConfig. If we use all these callbacks
together then they will execute in following order in bean life cycle.
1. First @PreDestroy will be called.
2. After that DisposableBean.destroy() will be called.
3. And then method specified by bean destroy-method in XML configuration is called.

9. Difference between close() and registerShutdownHook() in Spring?

● close() -- After calling close() method suddenly it will close the application
context and destroying all beans in bean factory.
● registerShutdownHook() -- After calling registerShutdownHook() method, it will
close application context and destroying all beans in bean factory when JVM
shutdown or after main method ends

ClassPathXmlApplicationContext context = new


ClassPathXmlApplicationContext("bean.xml");
StudentDAO studentDao = context.getBean("studentDao ",StudentDAO.class);
Sopln("studentDao ");
context.close();
StudentDAO studentDao = context.getBean("studentDao ",StudentDAO.class);
-->>In this, we will be getting exception because we are already closed the container so, we
can't get bean back.

ClassPathXmlApplicationContext context = new


ClassPathXmlApplicationContext("bean.xml");
StudentDAO studentDao = context.getBean("studentDao ",StudentDAO.class);
Sopln("studentDao ");
context.registerShutdownHook();
StudentDAO studentDao = context.getBean("studentDao ",StudentDAO.class);
-->>In this, we will not be getting exception because registerShutdownHook() method is
called after main() ends.

10. What is Dependency Injection in Spring?

❖ DI is a technique where one object supplies the dependency of another object.


❖ DI makes our programming code loosely coupled.
❖ By using Autowiring mechanism, we can achieve DI in spring.
there are two types of DI

Constructor Injection

private Employee employee;


// Constructor based DI
@Autowired
public Company(Employee employee) {
this.employee = employee;
}

Setter Injection

private Department department;


// Setter method based DI
@Autowired
public void setDepartment(Department department) {
this.department = department;

Field Injection

@Autowired
private Department department;

11. Difference between Setter and constructor injection?

● For mandatory dependencies or when aiming for immutability, use constructor


injection
● For optional or changeable dependencies, use setter injection

Setter Injection Constructor Injection

1. In Setter Injection, partial injection of 1. In constructor injection, partial


dependencies can possible, means if we have injection of dependencies cannot
3 dependencies like int, string, long, then its possible, because for calling
not necessary to inject all values if we use constructor we must pass all the
setter injection. If you are not inject it will arguments right, if not so we may get
takes default values for those primitives error

2. Setter Injection will overrides the 2. But, constructor injection cannot


constructor injection value, provided if we overrides the setter injected values
write setter and constructor injection for the
same property [i already told regarding this,
hope you remember ]

3. If we have more dependencies for example 3. In this case, Constructor injection is


15 to 20 are there in our bean class then, in highly recommended, as we can inject
this case setter injection is not recommended all the dependencies with in 3 to 4
as we need to write almost 20 setters right, lines [i mean, by calling one
bean length will increase. constructor]

4. Setter injection makes bean class object as 4. Constructor injection makes bean
mutable [We can change ] class object as immutable [We cannot
change ]

12. Why Field Injection is not recommended?

❖ You cannot create immutable objects, as you can with constructor injection
❖ Your classes have tight coupling with your DI container and cannot be used outside of
it.
❖ it can use private fields without public methods through reflection api and may get
class is unsafe.
❖ while declaring @Autowired on Field injection in eclipse IDE, it is saying “Field
Injection is not recommended”

11. What is autowired?

Autowiring means automatically injecting the dependent beans.


it is used for dependency injection in spring and used to automatically injects the
dependent beans into the associated references of a POJO class. This annotation will inject
the dependent beans by matching the data-type (i.e. Works internally as Autowiring
byType).
● @Autowired on the setter method (byName and byType)(setter Injection)
● @Autowired on constructor(constructor)(Constructor Injection)
● @Autowired on property(Field Injection)

12. What is dependency checking?

By default, the @Autowired will perform the dependency checking to make sure the
property has been wired properly. When Spring can’t find a matching bean to wire, it will
throw an exception. To fix it, you can disable this checking feature by setting the “required”
attribute of @Autowired to false.

@Autowired(required=false)

private Department department;

12. what is the use of @Qualifier?

Developers at present knew that if they are using Autowiring ‘byType’ mode than an
ambiguity exception is thrown at runtime if there are two or more beans for the same class
type. In this case, spring will not be able to choose the correct bean definition for the
injection purpose. Thus, to resolve this spring developer introduced the @Qualifier
annotation.

@Autowired(required=false)
@Qualifier(value = “department1”)
private Department department;

12. Difference between @Resource and @Autowired and @Qualifier?

❖ @Resource is the combination of @Autowired and @Qualifier.


❖ The difference are that @Autowired and @Qualifier are the spring annotation while
@Resource is the standard java annotation (from JSR-250) .
❖ It is suggested to use @Resource for fields and setter injection. @Qualifier and
@Autowired for constructor or a multi-argument method injection.

13. What is @Bean annotation?


The @Bean annotation tells Spring that a method annotated with @Bean will return an
object that should be registered as a bean in the Spring application context.
Spring @Bean method can be created within @Configuration and @Component classes. The
default scope of a bean is singleton.

14. Spring bean scopes?

5 types of bean scopes supported

1. singleton – Return a single bean instance per Spring IoC container


2. prototype – Return a new bean instance each time when requested

ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);

HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

https://javabeat.net/spring-bean-scopes-singleton-prototype/

3. request – Return a single bean instance per HTTP request. only valid in the context of
a web-aware Spring ApplicationContext
4. session – Return a single bean instance per HTTP session. only valid in the context of
a web-aware Spring ApplicationContext
5. globalSession – Return a single bean instance per global HTTP session. only valid in
the context of a web-aware Spring ApplicationContext and portlet applications.

https://javabeat.net/spring-bean-scopes-request-session-global-session-example/

In most cases, you may only deal with the Spring’s core scope – singleton and prototype,
and the default scope is singleton.

@RequestMapping(value = "/")

public String hellodata(Model model) {


model.addAttribute("requestscopedate", requestscopehellodata.getDate());

model.addAttribute("sessionscopedate", sessionscopehellodata.getDate());

/* return to view "hello.jsp" */

return "hello";

15. What do you understand by @Component annotation?

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-
managed component. The component-scanning mechanism of spring now can pick it up and
pull it into the application context.
16. What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method to a


specific class/ method in controller that will be handling the respective request. This
annotation can be applied at both levels:

● Class level : Maps the URL of the request


● Method level: Maps the URL as well as HTTP request method

17. What is Spring Interceptor :

When getting request from user, Dispatcher servlet will find the controller by using
handler mapping.

before executing the controller, Dispatcher servlet will check against the path
whether any interceptors are registered or not. if registered it executes the
prehandle and continue the process.

by using url and method type it will start to execute the controller method and
transfer the request to service. after getting the request from service repository get
data from database and send it to service.

after getting data, if any core or business logics will implement by service and
forward the response to controller. after getting response from service, controller
make the standard response by using response entity and send the model and view
response to dispatcher servlet.

after getting the response from controller, it will check whether post interceptors or
registered or not.

after executing the post interceptors, dispatcher servlet return the response to user.

Interceptors must implement HandlerInterceptorfrom the


org.springframework.web.servlet package. This interface defines three methods:

● preHandle is called before the actual handler is executed.


● postHandle is called after the handler is executed.

● afterCompletion is called after the complete request has finished.

package com.springapp.mvc;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.util.logging.Logger;

public class AuthInterceptor implements HandlerInterceptor {

private static final Logger logger = Logger.getLogger("AuthInterceptor");

@Override

public boolean preHandle(HttpServletRequest httpServletRequest,


HttpServletResponse httpServletResponse, Object o) throws Exception {

logger.info(" Pre handle ");

if(httpServletRequest.getMethod().equals("GET"))

return true;

else

return false;

@Override

public void postHandle(HttpServletRequest httpServletRequest,


HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
throws Exception {

logger.info(" Post handle ");

if(modelAndView.getModelMap().containsKey("status")){
String status = (String) modelAndView.getModelMap().get("status");

if(status.equals("SUCCESS!")){

status = "Authentication " + status;

modelAndView.getModelMap().put("status",status);

@Override

public void afterCompletion(HttpServletRequest httpServletRequest,


HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

logger.info(" After Completion ");

@Configuration

@EnableWebMvc

public class WebConfig extends WebMvcConfigurerAdapter {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(new
AuthInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");

registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");

}
18. Spring AOP?

Aspect Oriented Programming (AOP) compliments OOPs because it provides


modularity. But, the key unit of modularity here is considered as an aspect rather
than class. Here, AOP breaks the program logic into distinct parts (called concerns). It
is used to increase modularity by cross-cutting concerns.

Spring AOP module provides interceptors to intercept an application. For example,


when a method is executed, you can add extra functionality before or after the
method execution.

Aspect

This is a module which has a set of APIs providing cross-cutting requirements. For
example, a logging module would be called AOP aspect for logging. An application
can have any number of aspects depending on the requirement.

JoinPoint

We can use JoinPoint as a parameter in the advice methods and using it get the
method signature or the target object.

Advice

This is the actual action to be taken either before or after the method execution. This
is an actual piece of code that is invoked during the program execution by Spring
AOP framework.

Pointcut

This is a set of one or more join points where an advice should be executed. You can
specify pointcuts using expressions or patterns as we will see in our AOP examples.

AOP Advice Types

Based on the execution strategy of advice, they are of the following types.
1. Before Advice: These advices runs before the execution of join point methods.
We can use @Before annotation to mark an advice type as Before advice.

2. After (finally) Advice: An advice that gets executed after the join point method
finishes executing, whether normally or by throwing an exception. We can
create after advice using @After annotation.

3. After Returning Advice: Sometimes we want advice methods to execute only if


the join point method executes normally. We can use @AfterReturning
annotation to mark a method as after returning advice.

4. After Throwing Advice: This advice gets executed only when join point method
throws exception, we can use it to rollback the transaction declaratively. We
use @AfterThrowing annotation for this type of advice.

5. Around Advice: This is the most important and powerful advice. This advice
surrounds the join point method and we can also choose whether to execute
the join point method or not. We can write advice code that gets executed
before and after the execution of the join point method. It is the responsibility
of around advice to invoke the join point method and return values if the
method is returning something. We use @Around annotation to create around
advice methods.

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

@Aspect

public class EmployeeAspectPointcut {

@Before("getNamePointcut()")

public void loggingAdvice(){

System.out.println("Executing loggingAdvice on getName()");

@Before("getNamePointcut()")

public void secondAdvice(){

System.out.println("Executing secondAdvice on getName()");

@Pointcut("execution(public String getName())")


public void getNamePointcut(){}

@Before("allMethodsPointcut()")

public void allServiceMethodsAdvice(){

System.out.println("Before executing service method");

//Pointcut to execute on all the methods of classes in a package

@Pointcut("within(com.journaldev.spring.service.*)")

public void allMethodsPointcut(){}

@Before("execution(public void com.journaldev.spring.model..set*(*))")

public void loggingAdvice(JoinPoint joinPoint){

System.out.println("Before running loggingAdvice on


method="+joinPoint.toString());

System.out.println("Agruments Passed=" +
Arrays.toString(joinPoint.getArgs()));

In which scenario, you will use singleton and prototype scope?

Singleton scope should be used with stateless session bean and if thread safety not required
and prototype scope with stateful session bean and if thread safety required.
@Transactional

@Transactional annotation is used when you want the certain method/class(=all methods

inside) to be executed in a transaction.


Let's assume user A wants to transfer 100$ to user B. What happens is:
1. We decrease A's account by 100$
2. We add 100$ to B's account
Let's assume the exception is thrown after succeeding 1) and before executing 2). Now we
would have some kind of inconsistency because A lost 100$ while B got nothing.
Transactions means all or nothing. If there is an exception thrown somewhere in the
method, changes are not persisted in the database. Something called rollback happens.
If you don't specify @Transactional, each DB call will be in a different transaction.

When should I use @transactional?

The @Transactional should be used on service layer as it contains the business logic.
The DAO layer usually has only database CRUD operations. Service layer is best place
to add @Transactional annotations as most of the business logic present here, it
contain detail level use-case behaviour

Spring Boot

@SpringbootApplication

@EnableAutoConfiguration(exclude={DataSourceAutoConfig
uration.class})

how to log all apis request and responses in Spring boot?

@Configuration

public class RequestLoggingFilterConfig {

@Bean

public CommonsRequestLoggingFilter logFilter() {

CommonsRequestLoggingFilter filter

= new CommonsRequestLoggingFilter();

filter.setIncludeQueryString(true);

filter.setIncludePayload(true);

filter.setMaxPayloadLength(10000);

filter.setIncludeHeaders(false);

filter.setAfterMessagePrefix("REQUEST DATA : ");

return filter;
}

File application.properties:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilt
er=DEBUG

Spring boot starters :

Starters are a set of convenient dependency descriptors that you can include in your
application. ... If you want to develop a web application or an application to expose
restful services, Spring Boot Start Web is the starter to pick. Lets create a quick
project with Spring Boot Starter Web using Spring Initializr.

Spring profiles :

application-test.properties

application-prod.properties

java -jar springBootApp.jar --spring.profiles.active=test

Dependency resolution (Spring web, spring data jpa, test, mysql)

Component scan

@SpringBootApplication(@Configuration, @EnableAutoConfiguration, @ComponentScan)

SpringApplication.run(App.class, args);

Read Property files in SpringBoot

You can use @PropertySource to externalize your configuration to a properties file. There is
number of way to do get properties:
1. Assign the property values to fields by using @Value with
PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:
@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfiguration {

@Value("${gMapReportUrl}")
private String gMapReportUrl;

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}

}
2. Get the property values by using Environment:
@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfiguration {

@Autowired
private Environment env;

public void foo() {


env.getProperty("gMapReportUrl");
}

}
3. Read value from application.properties Using @ConfigurationProperties
In this we will map prefix of key using ConfigurationProperties and key name is same as
field of class
@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties
public class EmailConfig {

private String username;


}
Difference between JPA Repository and CRUD Repository :
JpaRepository extends PagingAndSortingRepository which in turn extends
CrudRepository.

Their main functions are:

● CrudRepository mainly provides CRUD functions.


● PagingAndSortingRepository provides methods to do pagination and sorting
records.
● JpaRepository provides some JPA-related methods such as flushing the
persistence context and deleting records in a batch.

Because of the inheritance mentioned above, JpaRepository will have all the functions of
CrudRepository and PagingAndSortingRepository. So if you don't need the repository to
have the functions provided by JpaRepository and PagingAndSortingRepository , use
CrudRepository

In order to achieve a fully working custom equality mechanism, it is


mandatory to override hashcode() each time you override equals().
Follow the tips below and you'll never have leaks in your custom equality
mechanism:

● If two objects are equal, they MUST have the same hash code.
● If two objects have the same hash code, it doesn't mean that they are
equal.
● Overriding equals() alone will make your business fail with hashing
data structures like: HashSet, HashMap, HashTable ... etc.
● Overriding hashcode() alone doesn't force Java to ignore memory
addresses when comparing two objects.

MySQL Queries : https://artoftesting.com/sql-queries-for-interview


Design Patterns

1. What is means design pattern?

Design patterns represent the best practices used by experienced object-oriented


software developers. Design patterns are solutions to general problems that software
developers faced during software development.

2. Types of Design Patterns?

1. Creational - How objects are created

2. Behavioral - How objects interact (behave) with each other

3. Structural - How objects are structured or laid out (relation with each other)

3. Singleton design pattern?


❖ Singleton design pattern is one of the gangs of four design pattern and falls
under creational design pattern and it is used for caching, creating driver
objects and logging objects.
❖ The main concept of singleton pattern is to create or return single object of
that class to save memory because values for the settings of all the objects
will be always same like every time we use new driver class it should return
me the old object instead of returning new object reference as the driver class
will never get changed.

❖ We can create singleton object by using 3 steps,


● Private constructor to restrict instantiation of the class from other
classes.
● Private static variable of the same class that is the only instance of the
class.
● Public static method that returns the instance of the class, this is the
global access point for outer world to get the instance of the singleton
class.

we can implement singleton object in many ways, example

1. Eager Instantiation

public class EagerSingleton {

// create an instance of the class.

private static EagerSingleton instance = new EagerSingleton();

// private constructor, so it cannot be instantiated outside this class.

private EagerSingleton() { }

// get the only instance of the object created.

public static EagerSingleton getInstance() {

return instance;

}
2. Static block initialization

public class StaticBlockSingleton {

private static final StaticBlockSingleton INSTANCE;

static {

try {

INSTANCE = new StaticBlockSingleton();

} catch (Exception e) {

throw new RuntimeException("Uffff, i was not expecting this!", e);

public static StaticBlockSingleton getInstance() {

return INSTANCE;

private StaticBlockSingleton() {

// ...

3. Lazy initializantion

public class LazySingleton {

// initialize the instance as null.

private static LazySingleton instance = null;

// private constructor, so it cannot be instantiated outside this class.

private LazySingleton() { }

// check if the instance is null, and if so, create the object.

public static LazySingleton getInstance() {


if (instance == null) {

instance = new LazySingleton();

return instance;

}}

4. Thread safe Singleton

public class ThreadSafeSingleton {

// initialize the instance as null.

private static ThreadSafeSingleton instance = null;

// private constructor, so it cannot be instantiated outside this class.

private ThreadSafeSingleton() { }

// check if the instance is null, within a synchronized block. If so, create


the object

public static ThreadSafeSingleton getInstance() {

synchronized (ThreadSafeSingleton.class) {

if (instance == null) {

instance = new ThreadSafeSingleton();

return instance;

For example, if the instance variable has already been instantiated, then each
time any client accesses the getInstance() method, the synchronized method
is run and the performance drops. This just happens in order to check if the
instance variables’ value is null. If it finds that it is, it leaves the method.
To reduce this overhead, double locking is used. The check is used before the
synchronized method as well, and if the value is null alone, does the
synchronized method run.

// double locking is used to reduce the overhead of the synchronized method

public static ThreadSafeSingleton getInstanceDoubleLocking() {

if (instance == null) {

synchronized (ThreadSafeSingleton.class) {

if (instance == null) {

instance = new ThreadSafeSingleton();

return instance;

How to break and prevent?

https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-
serialization-cloning/

4. Factory Design Pattern :

Factory Design pattern is one of the creational design pattern and as the name suggests it
uses factory class to create other classes of same type.

Factory pattern provides abstraction between implementation and client classes


through inheritance.

For example,
In my project, based on the client requirements, i want to return insurance type like
standard or premium. insurance type is extended by plans like standard and premium,
MacBook and HP and if a user need to get dell laptop it need to create it by itself and pass
all the required configuration. Similarly user need to be aware of the parameters required for
MacBook configuration and there can be n number of users and suppose any configuration
got changed in Mac class then all the users need to change their configuration parameters
instead we can have a laptop factory which will provide the required brand to each user.

This Factory class is like a factory of objects which manufactures objects based on client
inputs.

4. Prototype design pattern

Prototype design pattern is used when the Object creation is a costly affair and
requires a lot of time and resources and you have a similar object already existing.

Prototype pattern provides a mechanism to copy the original object to a new object
and then modify it according to our needs. Prototype design pattern uses java cloning
to copy the object.

Prototype Design Pattern Example

It would be easy to understand prototype design pattern with an example. Suppose


we have an Object that loads data from database. Now we need to modify this data
in our program multiple times, so it’s not a good idea to create the Object using new
keyword and load all the data again from database.

The better approach would be to clone the existing object into a new object and then
do the data manipulation.

Prototype design pattern mandates that the Object which you are copying should
provide the copying feature. It should not be done by any other class. However
whether to use shallow or deep copy of the Object properties depends on the
requirements and its a design decision.

Here is a sample program showing Prototype design pattern example in java.

Employees.java

package com.journaldev.design.prototype;
import java.util.ArrayList;

import java.util.List;

public class Employees implements Cloneable{

private List<String> empList;

public Employees(){

empList = new ArrayList<String>();

public Employees(List<String> list){

this.empList=list;

public void loadData(){

//read all employees from database and put into the list

empList.add("Pankaj");

empList.add("Raj");

empList.add("David");

empList.add("Lisa");

public List<String> getEmpList() {

return empList;

@Override

public Object clone() throws CloneNotSupportedException{

List<String> temp = new ArrayList<String>();

for(String s : this.getEmpList()){

temp.add(s);
}

return new Employees(temp);

Notice that the clone method is overridden to provide a deep copy of the employees
list.

Here is the prototype design pattern example test program that will show the benefit
of prototype pattern.

PrototypePatternTest.java

package com.journaldev.design.test;

import java.util.List;

import com.journaldev.design.prototype.Employees;

public class PrototypePatternTest {

public static void main(String[] args) throws CloneNotSupportedException {

Employees emps = new Employees();

emps.loadData();

//Use the clone method to get the Employee object

Employees empsNew = (Employees) emps.clone();

Employees empsNew1 = (Employees) emps.clone();

List<String> list = empsNew.getEmpList();

list.add("John");

List<String> list1 = empsNew1.getEmpList();

list1.remove("Pankaj");

System.out.println("emps List: "+emps.getEmpList());

System.out.println("empsNew List: "+list);


System.out.println("empsNew1 List: "+list1);

Output of the above prototype design pattern example program is:

If the object cloning was not provided, we will have to make database call to fetch
the employee list every time. Then do the manipulations that would have been
resource and time consuming.

Angular

1. What is TypeScript?

❖ Typescript is a client side scripting language for programming in Html page.

❖ it is a open-source programming language developed and maintained by


Microsoft.

❖ It is a typed superset of JavaScript means whatever we can do in javascript, it


is possible in typescript.
❖ basically, TypeScript is the ES6 version of JavaScript with some additional
features. so it supports all javascript features and additionally supports oop
features.

2. why we prefer typescript over java script and what is the difference?

❖ Java Script and Type script both are scripting language.

❖ but typescript supports more features than java script like oop features, static
typing, optional parameter and supports generics and modules.

3. Static typing

Compulsary we have to give variable type. so it can check errors at compile time itself.

4. What is angular?

Angular is a client-side TypeScript based framework maintained by google.

Angular is used to create dynamic web applications.

5. What is dynamic web applications?

Dynamic web applications are simply dynamic websites.

it will change data based on three parameters

● Time-to-time (eg. news update webs applications)

● Location-to-location (eg. Weather-report web applications)

● User-to-user (eg. Gmail, Facebook type applications)

6. What is Single Page Applications?

SPA means, In web application, Instead of loading new pages, it is rewriting the
content in same page dynamically.

Ex. Dynamic web applications

7. AngularJS vs Angular

1 Architecture Supports MVC design Pattern Uses Components and


directives
Language written in javascript. written in typescript.
2

Mobile Doesn’t provide any mobile provides mobiles support


support
3

Expression syntax {{}} are used to bind data uses () to bind an event
between view and model. and [] for property
Special methods, ng-bind can binding between view
4
also be used to do the same. and model.

Dependency Injection DI is not used. Hierarchical DI system is


used in Angular.
5

Routing @routeProvider.when, then are @Route configuration is


used to provide routing used to define routing
information. information.
6

Management AngularJS project is difficult to Angular code is better


manage with increasing size of structured, is easy to
the source code. create and manage
bigger applications.
7

angular.json :

it is the root level of an Angular workspace provides workspace-wide and project-


specific configuration defaults for build and development tools provided by the Angular
CLI.

package.json
Package.json is a list of all the dependencies of a project (among other things) that need to

be downloaded for the project. This includes version info for what needs to be downloaded.

tsConfig.json

The tsconfig. json file specifies the root files and the compiler options required to

compile the project.

main. ts file is the entry point of our web-app.It compiles the web-app and bootstraps

the AppModule to run in the browser. It starts with importing the basic module which we

need.

assets : we can store images, fonts like

environments : we can store configuration files

what is spring cloud ?

Spring Cloud, in microservices, is a system that provides integration with


external systems.

● Discovery of service registration.


● Service to service calls.
● Routing.
● Circuit breakers and load balancing.

Role of Actuator in Spring Boot


It is one of the most important features, which helps you to access the
current state of an application that is running in a production environment.

/actuator/health.

Service Discovery

Service discovery is how applications and (micro)services locate each other on a network. Service
discovery implementations include both:

● a central server (or servers) that maintain a global view of addresses and
● clients that connect to the central server to update and retrieve addresses.

What are microservices?


Microservices - also known as the microservice architecture - is an architectural style that structures
an application as a collection of services that are

● Highly maintainable and testable


● Loosely coupled
● Independently deployable
● Organized around business capabilities
● Owned by a small team
What is the difference between Monolithic, SOA and Microservices Architecture? What is the difference between Monolithic, SOA and Microservices Architecture?

@LoadBalanced

In Spring Cloud microservice application system, remote calls should be load balanced. When we
use RestTemplate as a remote call client, it's extremely simple to turn on load balancing: a
@LoadBalanced annotation is done. by using ribbon we can achieve. if 10 instances of service is
running , it should be load balance of which instance is currently free and want to call

if 10 instances of service is running , it should be load balance of which instance is currently free and
want to call

Http vs https

HTTPS is HTTP with encryption. The only difference between the two protocols is that
HTTPS uses TLS (SSL) to encrypt normal HTTP requests and responses. As a result,
HTTPS is far more secure than HTTP. A website that uses HTTP has http:// in its URL,
while a website that uses HTTPS has https://.

stateful and stateless difference :

A Stateful application remembers specific details of a user like profile, preferences,


and user actions. This information is considered as the ‘Status’ of a system.

For example, your shopping cart while using any website in Cloud. Each time you
select an item and add it in your cart, you add it with the items added previously and
eventually, you navigate to the checkout page.

In stateful, a server is required to maintain the current state and session information.

In stateful, server and client are tightly bound.

Ex. monolithic application, FTP, session cookies based authentication

A Stateless application or process is something that does not save or reference


information about previous operations. Every time it carries each operation from the
scratch just like the first time and provides functionality to use print, CDN (Content
Delivery Network) or the Web Servers in order to process every short-term request.

For example, someone is searching a question in the search engine and pressed the
Enter button. In case if the searching operation gets interrupted or closed due to
some reason, you have to start a new one as there is no saved data for your previous
request.

In Stateless, server is not needed to keep the server information or session details to
itself.

In stateless, server and client are loosely coupled and can act independently.

Ex. microservices, HTTP, JWT authentication


SessionCretionpolicy types

● Always during transactions without any constraints


(SessionCreationPolicy.ALWAYS)
● Only when required by the application (SessionCreationPolicy.IF_REQUIRED)
● Stop creating any but use existing sessions (SessionCreationPolicy.NEVER)
● Stop creating nor use sessions during the entire lifespan of the
application (SessionCreationPolicy.STATELESS)

A new instance of a persistent class which is not associated with a Session, has no
representation in the database and no identifier value is considered transient by Hibernate:
Person person = new Person(); person.setName("Foobar"); // person is in a
transient state

A persistent instance has a representation in the database, an identifier value and is


associated with a Session. You can make a transient instance persistent by associating it
with a Session:
Long id = (Long) session.save(person); // person is now in a persistent state

Now, if we close the Hibernate Session, the persistent instance will become a detached
instance: it isn't attached to a Session anymore (but can still be modified and reattached to
a new Session later though).

Webserver vs application server


1.Web server manage and execute web applications(war)

where as in Application server it manage and execute web applications


(war),Ejbcomponents (jar) and enterprise Applications (Ear).

2.Web Server uses only Servlet Container, Jspcontainer.

where as in application Server uses Servlet Container ,Jspcontainer ,EjbContainer.

3.web server Developed based on servlet ,Jsptechnologies of JEE module.

where asApplication Server devlopedbased on Servlet, Jsp,Ejb,Jms,Jta,Javamail of JEE.

4. Web server supports only http,httpsprotocol

Application server supports http,https,iiop,rmiprotocols.

5. web server Suitable for Small scale and medium scale web applications.

Application server Generally used for large scale.

6.Example of different webservers are Tomcat(Most popular), JWS,Reisn.

Different Application Servers are Weblogic,Jboos,Websphere

Simply

application Server=Web server+ EjbContainer+MailServer +other middle were Services

o the summary will be as follows-

Propagation Behaviour
REQUIRED Always executes in a transaction. If there is any
existing transaction it uses it. If none exists then
only a new one is created

SUPPORTS It may or may not run in a transaction. If current


transaction exists then it is supported. If none
exists then gets executed with out transaction.

NOT_SUPPORT Always executes without a transaction. If there


ED is any existing transaction it gets suspended

REQUIRES_NE Always executes in a new transaction. If there is


W any existing transaction it gets suspended

NEVER Always executes with out any transaction. It


throws an exception if there is an existing
transaction

MANDATORY Always executes in a transaction. If there is any


existing transaction it is used. If there is no existing
transaction it will throw an exception.
● Dirty Reads - Suppose two transactions - Transaction A and Transaction
B are running concurrently. If Transaction A modifies a record but not
commits it. Transaction B reads this record but then Transaction A again
rollbacks the changes for the record and commits it. So Transaction B has
a wrong value.
● Non-Repeatable Reads - Suppose two transactions - Transaction A and
Transaction B are running concurrently. If Transaction A reads some
records. Transaction B modifies these records before transaction A has
been committed. So if Transaction A again reads these records they will be
different. So same select statements result in different existing records.
● Phantom Reads - Suppose two transactions - Transaction A and
Transaction B are running concurrently. If Transaction A reads some
records. Transaction B adds more such records before transaction A has
been committed. So if Transaction A again reads there will be more
records than the previous select statement. So same select statements
result in different number records to be displayed as new records also get
added.

Isolation Level Dirty Re Non- Phantom


Repeatable Reads
ads
Reads
SERIALIZABLE This This This
scenario is scenario is scenario is
not possible not possible not possible
as the as the as the
second second second
transaction transaction transaction
cannot start cannot start cannot start
execution execution execution
until the first until the first until the first
is is is
committed. committed. committed.
They never They never They never
execute execute execute
parallelly parallelly parallelly
but only but only but only
sequentially sequentially sequentially

REPEATABLE_READ This This This


scenario is scenario is scenario is
not possible not possible possible as
as any since any other
existing record can transactions
record be changed can insert
change gets only after a new records
reflected transaction even if first
only if the has been transaction
transaction committed. commit has
is So multiple not taken
committed. select place.
So other statements
transaction before
will never transaction
read wrong commit will
value. always
return same
existing
records.

READ_COMMITTED This This This


scenario is scenario is scenario is
not possible possible as possible as
as any other other
existing transactions transactions
record can modify can insert
change gets existing new records
reflected records even if first
only if the even if first transaction
transaction transaction commit has
is commit has not taken
committed. not taken place.
So other place.
transaction
will never
read wrong
value.

READ_UNCOMMITTE This This This


D scenario is scenario is scenario is
possible as possible possible as
any record since any any record
can be read record can can be
by other be changed inserted
transactions even if a even if a
even if the transaction transaction
first is not is not
transaction committed. committed.
is not
committed.
So if first
transaction
rollbacks
the record
changes
then other
transactions
will have
wrong
values

Cascade Description
Operations

PERSIST In this cascade operation, if the parent entity is persisted then all its

related entity will also be persisted.

MERGE In this cascade operation, if the parent entity is merged then all its

related entity will also be merged.

DETACH In this cascade operation, if the parent entity is detached then all its

related entity will also be detached.

REFRESH In this cascade operation, if the parent entity is refreshed then all its

related entity will also be refreshed.

REMOVE In this cascade operation, if the parent entity is removed then all its
related entity will also be r ,≥emoved.

ALL In this case, all the above cascade operations can be applied to the

entities related to parent entity.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
:
This page is created from HTTP status code information found at ietf.org and Wikipedia. Click on the
category heading or the status code link to read more.

1xx Informational
100 Continue

101 Switching Protocols

102 Processing (WebDAV)

2xx Success
200 OK




201 Created

202 Accepted

203 Non-Authoritative Information

204 No Content

205 Reset Content

206 Partial Content




207 Multi-Status (WebDAV)

208 Already Reported (WebDAV)

226 IM Used
3xx Redirection
300 Multiple Choices

301 Moved Permanently

302 Found

303 See Other

304 Not Modified



305 Use Proxy

306 (Unused)

307 Temporary Redirect

308 Permanent Redirect (experimental)

4xx Client Error


400 Bad Request

401 Unauthorized

402 Payment Required

403 Forbidden

404 Not Found

405 Method Not Allowed

406 Not Acceptable

407 Proxy Authentication Required

408 Request Timeout

409 Conflict

410 Gone
411 Length Required

412 Precondition Failed

413 Request Entity Too Large

414 Request-URI Too Long

415 Unsupported Media Type

416 Requested Range Not Satisfiable

417 Expectation Failed

418 I'm a teapot (RFC 2324)

420 Enhance Your Calm (Twitter)

422 Unprocessable Entity (WebDAV)

423 Locked (WebDAV)

424 Failed Dependency (WebDAV)

425 Reserved for WebDAV

426 Upgrade Required

428 Precondition Required

429 Too Many Requests

431 Request Header Fields Too Large

444 No Response (Nginx)

449 Retry With (Microsoft)

450 Blocked by Windows Parental Controls (Microsoft)

451 Unavailable For Legal Reasons

499 Client Closed Request (Nginx)

5xx Server Error


500 Internal Server Error
501 Not Implemented

502 Bad Gateway

503 Service Unavailable

504 Gateway Timeout

505 HTTP Version Not Supported

506 Variant Also Negotiates (Experimental)

507 Insufficient Storage (WebDAV)

508 Loop Detected (WebDAV)

509 Bandwidth Limit Exceeded (Apache)

510 Not Extended

511 Network Authentication Required

598 Network read timeout error

599 Network connect timeout error

You might also like