What is Spring Framework
What is Spring Framework
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 :
1. Core Container
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.
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
5. Instrumentation
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)?
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?
BeanFactory
ApplicationContext
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.
● 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
Constructor Injection
Setter Injection
Field Injection
@Autowired
private Department department;
4. Setter injection makes bean class object as 4. Constructor injection makes bean
mutable [We can change ] class object as immutable [We cannot
change ]
❖ 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”
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)
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;
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 = "/")
model.addAttribute("sessionscopedate", sessionscopehellodata.getDate());
return "hello";
@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?
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.
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;
@Override
if(httpServletRequest.getMethod().equals("GET"))
return true;
else
return false;
@Override
if(modelAndView.getModelMap().containsKey("status")){
String status = (String) modelAndView.getModelMap().get("status");
if(status.equals("SUCCESS!")){
modelAndView.getModelMap().put("status",status);
@Override
@Configuration
@EnableWebMvc
@Override
registry.addInterceptor(new
AuthInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
}
18. Spring AOP?
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.
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.
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
@Before("getNamePointcut()")
@Before("getNamePointcut()")
@Before("allMethodsPointcut()")
@Pointcut("within(com.journaldev.spring.service.*)")
System.out.println("Agruments Passed=" +
Arrays.toString(joinPoint.getArgs()));
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
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})
@Configuration
@Bean
CommonsRequestLoggingFilter filter
= new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(false);
return filter;
}
File application.properties:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilt
er=DEBUG
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
Component scan
SpringApplication.run(App.class, args);
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;
}
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 {
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
● 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.
3. Structural - How objects are structured or laid out (relation with each other)
1. Eager Instantiation
private EagerSingleton() { }
return instance;
}
2. Static block initialization
static {
try {
} catch (Exception e) {
return INSTANCE;
private StaticBlockSingleton() {
// ...
3. Lazy initializantion
private LazySingleton() { }
return instance;
}}
private ThreadSafeSingleton() { }
synchronized (ThreadSafeSingleton.class) {
if (instance == null) {
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.
if (instance == null) {
synchronized (ThreadSafeSingleton.class) {
if (instance == null) {
return instance;
https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-
serialization-cloning/
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.
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.
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.
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.
Employees.java
package com.journaldev.design.prototype;
import java.util.ArrayList;
import java.util.List;
public Employees(){
this.empList=list;
//read all employees from database and put into the list
empList.add("Pankaj");
empList.add("Raj");
empList.add("David");
empList.add("Lisa");
return empList;
@Override
for(String s : this.getEmpList()){
temp.add(s);
}
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;
emps.loadData();
list.add("John");
list1.remove("Pankaj");
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?
2. why we prefer typescript over java script and what is the difference?
❖ 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?
SPA means, In web application, Instead of loading new pages, it is rewriting the
content in same page dynamically.
7. AngularJS vs Angular
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.
angular.json :
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
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.
/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.
@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://.
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.
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.
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
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).
5. web server Suitable for Small scale and medium scale web applications.
Simply
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
Cascade Description
Operations
PERSIST In this cascade operation, if the parent entity is persisted then all its
MERGE In this cascade operation, if the parent entity is merged then all its
DETACH In this cascade operation, if the parent entity is detached then all its
REFRESH In this cascade operation, if the parent entity is refreshed then all its
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
● (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
2xx Success
200 OK
●
●
●
●
201 Created
202 Accepted
204 No Content
●
●
●
●
226 IM Used
3xx Redirection
300 Multiple Choices
302 Found
●
●
●
306 (Unused)
401 Unauthorized
403 Forbidden
409 Conflict
410 Gone
411 Length Required