Wednesday, October 30, 2019

Spring Interview Questions - Basic To Advance - Part 5 Spring JDBC & Transaction Management

How would you achieve Transaction Management in Spring?
Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.

We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure transaction manager for the DataSource in the spring bean configuration file.

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

How to use Tomcat JNDI DataSource in Spring Web Application?
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.

Sample configuration would be:
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
     <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</beans:bean>

What are the benefits of the Spring Framework’s transaction management?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:

Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
Integrates very well with Spring’s various data access abstractions.
Spring resolves the disadvantages of global and local transactions. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. The Spring Framework provides both declarative and programmatic transaction management.

Spring JDBC Implementation
https://www.topjavatutorial.com/frameworks/spring/spring-jdbc/spring-jdbc-using-annotation-based-configuration/

JdbcTemplate for Insert, Update and Delete operations
String sql = "insert into employee(age,name) values(?,?)";
        jdbcTemplate.update(sql,new Object[]{emp.getAge(),emp.getName()});


JdbcTemplate for Querying data
JdbcTemplate offers various methods like query(), queryForInt(), queryForLong(),
queryForObject(), queryForList(), queryForMap(), and queryForRowSet() methods that we can use to query data.

String sql = "select * from employee where id = ?";
        Employee emp = jdbcTemplate.queryForObject(sql,new Object[]{id}, new RowMapper<Employee>(){

            public Employee mapRow(ResultSet rs, int rownum)
                    throws SQLException {
                Employee emp = new Employee();
                emp.setId(rs.getInt("id"));
                emp.setAge(rs.getInt("age"));
                emp.setName(rs.getString("name"));
                return emp;
            }
         
        });

JdbcTemplate to execute DDL statements


    public void CreateEmployeeTable(){
        String sql = " CREATE TABLE Employee(ID INT PRIMARY KEY AUTO_INCREMENT, AGE INT,NAME VARCHAR(255)); ";
        jdbcTemplate.execute(sql);
    }

JDBCTeamplate Batch Update
https://examples.javacodegeeks.com/enterprise-java/spring/jdbc/spring-jdbctemplate-example/

Calling SP from Spring
https://javarevisited.blogspot.com/2013/04/spring-framework-tutorial-call-stored-procedures-from-java.html

Tuesday, October 29, 2019

Spring Interview Questions - Basic To Advance - Part 4

What is Spring AOP?
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.


What is Aspect, Advice, Join point and pointcut in Spring AOP?
Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name.

Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.

Advice : Action taken by  aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.

Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.

What is @Qualifier annotation in Spring?

You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.

What is @Required annotation in Spring?
This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.

Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.

Circular dependencies in Spring
For example: Class A requires an instance of Class B and Class B requires an instance of Class A.
As you can see, we are getting BeanCurrentlyInCreationException.Requested bean is currently in creation: Is there an unresolvable circular reference?

Solution

Setter injection
You use @Lazy with @Autowired to solve circular dependencies in Spring.
public class A {
 B b;
 @Autowired
 public A(@Lazy B b) {
  super();
  this.b = b;
 }
}

You use @PostConstruct with @Autowired to solve circular dependencies in Spring.
@PostConstruct
 public void init()
 {
  b.setA(this);
 }

What happens when you inject prototype bean into singleton bean? Can you explain the behavior?
When you inject prototype bean to singleton bean, prototype bean still behave like a singleton bean.

Solution

There are many ways to solve this problem.

Using Method injection
@Lookup

 public Y getY() {
  return y;
 }

You can use method injection to solve this problem.Simply use @Lookup with getY() method, it will return new instance each time.

Spring will use CGLIB to generate dynamically a subclass that overrides the method getY(). It then registers the bean into the application context. Whenever we request for getY() method, it will return new instance of Class Y.
There are two options here, either create dummy method or mark method as abstract. When you mark method as abstract, then you will have to declare class abstract as well, hence we have used dummy method in this scenario.

Using ObjectFactory

You can use ObjectFactory to get new object each time getY() method is called.
@Autowired
 private ObjectFactory<Y> prototypeBeanObjectFactory;
 Y y;
 public Y getY() {
  return prototypeBeanObjectFactory.getObject();
 }

Using ApplicationContextAware
You can return new bean using application context wheneven getY() method is getting called.
public class X implements ApplicationContextAware{
 private ApplicationContext applicationContext;
 Y y;
 public Y getY() {
  return applicationContext.getBean(Y.class);
 }
 public void setY(Y y) {
  this.y = y;
 }
 @Override
 public void setApplicationContext(ApplicationContext arg0) throws BeansException {
  this.applicationContext=arg0;
 }
}
Link : https://java2blog.com/spring-interview-questions-and-answers/

ContextLoaderListener vs DispatcherServlet vs Application Context vs Web Application Context - Decrypting the myth
https://siddharthnawani.blogspot.com/2019/10/contextloaderlistener-vs.html

Scope of a Spring-Controller and its instance-variables
https://stackoverflow.com/questions/11139571/scope-of-a-spring-controller-and-its-instance-variables

https://www.stacktips.com/tutorials/spring/how-spring-controller-request-mapping-works-in-spring-mvc


@Named annotation in Spring MVC
@Named works the same as @Component. However, the annotations @Controller, @Service, and @Repository are more specific.

From the Spring docs:

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

This section explains the difference with @Named.

Many components, like Spring's DispatcherServlet (MVC configuration in WebApplicationContext) aren't looking for Component, they are looking for @Controller. So when it scans your class, it won't find it in @Named. In a similar fashion, transaction management with @Transactional looks for @Service and @Repository, not for the more generic @Component.

Spring Interview Questions - Basic To Advance - Part 3 Spring MVC

Which ViewResolver class is widely used?
The org.springframework.web.servlet.view.InternalResourceViewResolver class is widely used.


What is DispatcherServlet and ContextLoaderListener?
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.



What is ViewResolver in Spring?
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
          <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/" />

<beans:property name="suffix" value=".jsp" />

</beans:bean>

          <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/" />

<beans:property name="suffix" value=".jsp" />

</beans:bean>

InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.

How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following ways to help us achieving robust exception handling.
Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

What are the minimum configurations needed to create Spring MVC application?
For creating a simple Spring MVC application, we would need to do following tasks.
Add spring-context and spring-webmvc dependencies in the project.
Configure DispatcherServlet in the web.xml file to handle requests through spring container.
Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC application.

Can we send an Object as the response of Controller handler method?
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.

Warning: “The type WebMvcConfigurerAdapter is deprecated”

This warning will appear if we're using Spring version 5 (or Spring Boot 2), either when upgrading an existing application or building a new application with the old API.

Let's briefly go through the history behind it.

In earlier versions of Spring, up to and including version 4, if we wanted to configure a web application, we could make use of the WebMvcConfigurerAdapter class:

@Configuration
public WebConfig extends WebMvcConfigurerAdapter {
   
    // ...
}
This is an abstract class that implements the WebMvcConfigurer interface and contains empty implementations for all the methods inherited.

By subclassing it, we can override its methods, which provide hooks into various MVC configuration elements such as view resolvers, interceptors and more.

However, Java 8 added the concept of default methods in interfaces. Naturally, the Spring team updated the framework to make full use of the new Java language features.

As mentioned, the WebMvcConfigurer interface, starting with Spring 5, contains default implementations for all its methods. As a result, the abstract adapter class was marked as deprecated.

Let's see how we can start using the interface directly and get rid of the warning:

@Configuration
public WebConfig implements WebMvcConfigurer {
    // ...
}

https://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/


WebMvcConfigure is the replacement of applicationContext.xml

one needs to implement WebApplicationInitializer to get rid of web.xml or extends AbstractAnnotationConfigDispatcherServletInitializer

Example:

For bootstrapping the application.

public class MyWebApplicationInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer
{

    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {RootConfig.class};
    }

    protected Class<?>[] getServletConfigClasses()  {
        return new Class[] {WebConfiguration .class};
    }

    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

Ex #2
@Configuration
public class CustomDispatcherServlet implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext dispatcherServletContext = new AnnotationConfigWebApplicationContext();

        dispatcherServletContext.register(CustomDispatcherConfig.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherServletContext);

        // Create a servlet dynamically.
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", dispatcherServlet);

        dispatcher.setLoadOnStartup(1);

        // Add servlet mapping url. All url end with .html will be processed by this servlet.
        dispatcher.addMapping("*.html");
    }

What is a MultipartResolver and when its used?
MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.

Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it

How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following ways to achieve robust exception handling.

Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

Spring MVC

How to validate form data in Spring Web MVC Framework?
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.



What are Spring MVC Interceptor and how to use it?
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.

We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.

The handler interceptor have to implement the HandlerInterceptor interface, which contains three methods :

preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.
postHandle() – Called after the handler execution, allow manipulate the ModelAndView object before render it to view page.
afterCompletion() – Called after the complete request has finished. Seldom use, cant find any use case.

How do you load and inject properties into a Spring Bean?

Let’s say we have a message.properties file that defines a database connection timeout property called connection.timeout. To load this property into a Spring context, we need to define a propertyConfigurer bean:
 <bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
     <property name="location" value="/WEB-INF/message.properties" />
</bean>

After that we can use Spring Expression Language to inject properties into other beans:

<bean class="com.learningsolo.spring.ConnectionFactory">
     <property name="timeout" value="${connection.timeout}"/>
</bean>

The same is available in the annotation based configuration, like so:
@Value("${connection.timeout}")
private int timeout;

What are the different ways to configure a class as Spring Bean?
There are multiple ways to configure Spring Bean: XML configuration, Java based configuration and annotation based configuration.

XML configuration
<bean id="myBean" class="com.learningsolo.spring.MyBean"/>

Java Based Configuration
ConfigurableApplicationContext context;
context.getBeanFactory().registerSingleton(name, obj);

Annotation Based Configuration
A Spring Bean can be configured with the @Bean annotation, which is used together with @Configuration classes.

@Configuration
public class MyConfiguration {
    @Bean
    public MyService getService(){
        return new MyService();
    }
}

Annotations Based : Annotations @Component, @Service, @Repository and @Controller can also be used with classes to configure them as Spring Beans. In this case, the base package location has to be provided to scan for these classes, like so:
<context:component-scan base-package=”com.learningsolo.spring” />




Monday, October 28, 2019

Spring Bean Life Cycle

Spring Bean Life-Cycle



Spring Context is also responsible for injection dependencies in the bean, either through setter or constructor methods or by spring autowiring.

Sometimes we want to initialize resources in the bean classes, for example creating database connections or validating third party services at the time of initialization before any client request. Spring framework provide different ways through which we can provide post-initialization and pre-destroy methods in a spring bean life cycle.

Life cycle callbacks

Post-initialization call back methods
Pre-destruction call back methods


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

InitializingBean and DisposableBean callback interfaces
*Aware interfaces for specific behavior
Custom init() and destroy() methods in bean configuration file
@PostConstruct and @PreDestroy annotations


InitializingBean and DisposableBean

The org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container.

The InitializingBean interface specifies a single method:

InitializingBean.java
void afterPropertiesSet() throws Exception;
This is not a preferrable way to initialize the bean because it tightly couple your bean class with spring container. A better approach is to use “init-method” attribute in bean definition in applicationContext.xml file.

Similarly, implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed.

The DisposableBean interface specifies a single method:

DisposableBean.java
void destroy() throws Exception;

A sample bean implementing above interfaces would look like this:


package com.howtodoinjava.task;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class DemoBean implements InitializingBean, DisposableBean
{
    //Other bean attributes and methods
   
    @Override
    public void afterPropertiesSet() throws Exception
    {
        //Bean initialization code
    }
   
    @Override
    public void destroy() throws Exception
    {
        //Bean destruction code
    }
}


*Aware interfaces for specific behavior
Spring offers a range of *Aware interfaces that allow beans to indicate to the container that they require a certain infrastructure dependency. Each interface will require you to implement a method to inject the dependency in bean.

Custom init() and destroy() methods
The default init and destroy methods in bean configuration file can be defined in two ways:

Bean local definition applicable to a single bean
Global definition applicable to all beans defined in beans context
Bean local definition
Local definition is given as below.

beans.xml
<beans>

    <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"
                    init-method="customInit"
                    destroy-method="customDestroy"></bean>

</beans>
. Global definition
Where as global definition is given as below. These methods will be invoked for all bean definitions given under <beans> tag. They are useful when you have a pattern of defining common method names such as init() and destroy() for all your beans consistently. This feature helps you in not mentioning the init and destroy method names for all beans independently.

<beans default-init-method="customInit" default-destroy-method="customDestroy"> 

        <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"></bean>

</beans>
Java program to show methods configured in bean XML configuration file.

DemoBean.java
package com.howtodoinjava.task;

public class DemoBean
{
    public void customInit()
    {
        System.out.println("Method customInit() invoked...");
    }

    public void customDestroy()
    {
        System.out.println("Method customDestroy() invoked...");
    }
}

 @PostConstruct and @PreDestroy
Spring 2.5 onwards, you can use annotations also for specifying life cycle methods using @PostConstruct and @PreDestroy annotations.

@PostConstruct annotated method will be invoked after the bean has been constructed using default constructor and just before it’s instance is returned to requesting object.
@PreDestroy annotated method is called just before the bean is about be destroyed inside bean container.
Java program to show usage of annotation configuration to control using annotations.

package com.howtodoinjava.task;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class DemoBean
{
    @PostConstruct
    public void customInit()
    {
        System.out.println("Method customInit() invoked...");
    }
   
    @PreDestroy
    public void customDestroy()
    {
        System.out.println("Method customDestroy() invoked...");
    }
}


Spring Bean Life Cycle Important Points:

Spring Context is first using no-args constructor to initialize the bean object and then calling the post-init method.
The order of bean initialization is same as it’s defined in the spring bean configuration file.
The context is returned only when all the spring beans are initialized properly with post-init method executions.
When context is getting closed, beans are destroyed in the reverse order in which they were initialized i.e in LIFO (Last-In-First-Out) order.


Route of Spring Bean :

Aware Interfaces ( setBeanFactory() -> setBeanName() - > setApplicationContext())

-> Bean Post Processor (postProcessBeforeInitialization -> postProcessAfterInitialization)

- > InitializingBean and DisposableBean Callback Interfaces

-> Cuton Init & Destroy

 




References :
https://www.journaldev.com/2637/spring-bean-life-cycle
https://howtodoinjava.com/spring-core/spring-bean-life-cycle/
https://dzone.com/articles/spring-bean-lifecycle

Saturday, October 26, 2019

ContextLoaderListener vs DispatcherServlet vs Application Context vs Web Application Context - Decrypting the myth

Root and child contexts
Before reading further, please understand that –

Spring can have multiple contexts at a time. One of them will be root context, and all other contexts will be child contexts.

All child contexts can access the beans defined in root context; but opposite is not true. Root context cannot access child contexts beans.


ApplicationContext :

applicationContext.xml is the root context configuration for every web application.
Spring loads applicationContext.xml file and creates the ApplicationContext for the whole application.
There will be only one application context per web application.
If you are not explicitly declaring the context configuration file name in web.xml using the contextConfigLocation param, Spring will search for the applicationContext.xml under WEB-INF folder and throw FileNotFoundException if it could not find this file.

ContextLoaderListener
Performs the actual initialization work for the root application context.
Reads a “contextConfigLocation” context-param and passes its value to the context instance, parsing it into potentially multiple file paths which can be separated by any number of commas and spaces, e.g. “WEB-INF/applicationContext1.xml, WEB-INF/applicationContext2.xml”.
ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener, just a basic minimum web.xml with DispatcherServlet.

DispatcherServlet 
DispatcherServlet is essentially a Servlet (it extends HttpServlet) whose primary purpose is to handle incoming web requests matching the configured URL pattern. It take an incoming URI and find the right combination of controller and view. So it is the front controller.

When you define a DispatcherServlet in spring configuration, you provide an XML file with entries of controller classes, views mappings etc. using contextConfigLocation attribute.

WebApplicationContext
Apart from ApplicationContext, there can be multiple WebApplicationContext in a single web application.
In simple words, each DispatcherServlet associated with single WebApplicationContext.
xxx-servlet.xml file is specific to the DispatcherServlet and a web application can have more than one DispatcherServlet configured to handle the requests.
In such scenarios, each DispatcherServlet would have a separate xxx-servlet.xml configured. But, applicationContext.xml will be common for all the servlet configuration files.
Spring will by default load file named “xxx-servlet.xml” from your webapps WEB-INF folder where xxx is the servlet name in web.xml.
If you want to change the name of that file name or change the location, add initi-param with contextConfigLocation as param name.


Comparison and relation between them :

ContextLoaderListener vs DispatcherServlet

ContextLoaderListener creates root application context.
DispatcherServlet entries create one child application context per servlet entry.
Child contexts can access beans defined in root context.
Beans in root context cannot access beans in child contexts (directly).
All contexts are added to ServletContext.
You can access root context using WebApplicationContextUtils class.


After reading the Spring documentation, following is the understanding:

a) Application-Contexts are hierarchial and so are WebApplicationContexts. Refer documentation here.

b) ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).

c) DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this context.

d) When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. Refer documentation here.




When we are working with Spring MVC and are also using Spring in the services layer, we provide two application-contexts. The first one is configured using ContextLoaderListener and the other with DispatcherServlet

Generally, you will define all MVC related beans (controller and views etc) in DispatcherServlet context, and all cross-cutting beans such as security, transaction, services etc. at root context by ContextLoaderListener.


References :

https://javabeat.net/spring-mvc-application-context/
https://schoudari.wordpress.com/2012/07/23/purpose-of-contextloaderlistener-spring-mvc/
https://howtodoinjava.com/spring-mvc/contextloaderlistener-vs-dispatcherservlet/




Spring Interview Questions - Basic To Advance - Part 2

 What is Spring AOP?
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.

What is Spring AOP?
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.

What is Aspect, Advice, Join point and pointcut in Spring AOP?
Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name.
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by  aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.

Example : https://www.javainuse.com/spring/spring-boot-aop

What is @Qualifier annotation in Spring?
You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.


What is @Required annotation in Spring?
This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.
Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.

Circular dependencies in Spring
For example: Class A requires an instance of Class B and Class B requires an instance of Class A.

As you can see, we are getting BeanCurrentlyInCreationException.Requested bean is currently in creation: Is there an unresolvable circular reference?

Solution

Setter injection
You use @Lazy with @Autowired to solve circular dependencies in Spring.
public class A {

B b;

@Autowired
public A(@Lazy B b) {
super();
this.b = b;
}

}

You use @PostConstruct with @Autowired to solve circular dependencies in Spring.

@PostConstruct
public void init()
{
b.setA(this);
}

What happens when you inject prototype bean into singleton bean? Can you explain the behavior?
When you inject prototype bean to singleton bean, prototype bean still behave like a singleton bean.
Solution
There are many ways to solve this problem.

Using Method injection
@Lookup
public Y getY() {
return y;
}

You can use method injection to solve this problem.Simply use @Lookup with getY() method, it will return new instance each time.
Spring will use CGLIB to generate dynamically a subclass that overrides the method getY(). It then registers the bean into the application context. Whenever we request for getY() method, it will return new instance of Class Y.

There are two options here, either create dummy method or mark method as abstract. When you mark method as abstract, then you will have to declare class abstract as well, hence we have used dummy method in this scenario.

Using ObjectFactory
You can use ObjectFactory to get new object each time getY() method is called.

@Autowired
    private ObjectFactory<Y> prototypeBeanObjectFactory;

Y y;

public Y getY() {
return prototypeBeanObjectFactory.getObject();
}

Using ApplicationContextAware
You can return new bean using application context wheneven getY() method is getting called.

public class X implements ApplicationContextAware{

private ApplicationContext applicationContext;

Y y;

public Y getY() {
return applicationContext.getBean(Y.class);
}

public void setY(Y y) {
this.y = y;
}

@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
this.applicationContext=arg0;
}
}

Link https://java2blog.com/spring-interview-questions-and-answers/


What is the difference between Bean Factory and ApplicationContext?

BeanFactory is also called basic IOC and ApplicationContext is called Advanced IOC. Although BeanFactory and ApplicationContext both are used to get the beans from IOC container by using method getBean(String beanName). But they have some significant differences in their implementation which are described as below :
BeanFactory uses lazy initialization approach whereas ApplicationContext uses eager initialization approach.i.e BeanFactory creates a singleton bean only when it is requested from it but ApplicationContext creates all singleton beans at the time of its own initialization.
ApplicationContext supports internationalization but BeanFactory do not.
Annotation based dependency Injection is not supported by BeanFactory whereas ApplicationContext supports using annotation @PreDestroy, @Autowired.
The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring’s AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.

In which scenario, you will use singleton and prototype scope?
Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.


Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.


What are some of the important Spring annotations you have used?

Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation.
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc

Name some of the design patterns used in Spring Framework?
Spring Framework is using a lot of design patterns, some of the common ones are:
Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming


What are the types of the transaction management Spring support?
Spring supports two types of transaction management:
Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.

Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.


Which are the important beans lifecycle methods?

https://siddharthnawani.blogspot.com/2019/10/spring-bean-life-cycle.html


How can you inject a Java Collection in Spring?
Spring offers the following types of collection configuration elements:
The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
The <set> type is used for wiring a set of values but without any duplicates.
The <map> type is used to inject a collection of name-value pairs where name and value can be of any type.
The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.


What is bean auto wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.


Explain different modes of auto wiring?
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
no: This is default setting. Explicit bean reference should be used for wiring.

byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.

constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.


Are there limitations with autowiring?

Limitations of autowiring are:
Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.


Difference between Setter Injection and Constructor Injection
https://codenuclear.com/difference-between-setter-injection-and-constructor-injection/


Are Singleton beans thread safe in Spring Framework?

Spring framework does not do anything under the hood concerning the multi-threaded behavior of a singleton bean. It is the developer’s responsibility to deal with concurrency issue and thread safety of the singleton bean.
While practically, most spring beans have no mutable state (e.g. Service and DAO clases), and as such are trivially thread safe. But if your bean has mutable state (e.g. View Model Objects), so you need to ensure thread safety. The most easy and obvious solution for this problem is to change bean scope of mutable beans from “singleton” to “prototype“.


How do you turn on annotation based autowiring?

<beans>
    <context:annotation-config />
</beans>


 What are the different types of events in spring framework?
Spring’s ApplicationContext provides the functionality to support events and listeners in code. We can create beans that listen for events which are published through our ApplicationContext. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.

public class AllApplicationEventListener implements ApplicationListener < ApplicationEvent >

{

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent)
    {      //process event
    }
}

Spring provides the following 5 standard events:
ContextRefreshedEvent : This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextStartedEvent : This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
ContextStoppedEvent : This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required house keeping work after receiving this event.
ContextClosedEvent : This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
RequestHandledEvent : This is a web-specific event telling all beans that an HTTP request has been serviced.
Apart from above, you can create your own custom events by extending ApplicationEvent class. e.g.

public class CustomApplicationEvent extends ApplicationEvent
{
    public CustomApplicationEvent ( Object source, final String msg )
    {
        super(source);
       System.out.println("Created a Custom event");
    }
}

To listen this event, create a listener like this:
public class CustomEventListener implements ApplicationListener < CustomApplicationEvent >
{
    @Override
    public void onApplicationEvent(CustomApplicationEvent applicationEvent) {
        //handle event
    }
}

And to publish this event, you will need the help of applicationContext instance.
CustomApplicationEvent customEvent = new CustomApplicationEvent( applicationContext, "Test message" );
applicationContext.publishEvent ( customEvent );


Name some of the design patterns used in Spring Framework?
There are loads of different design patterns used, but there are a few obvious ones:
Proxy – used heavily in AOP, and remoting.
Singleton – beans defined in spring config files are singletons by default.

Template method – used extensively to deal with boilerplate repeated code e.g. RestTemplate, JmsTemplate, JpaTemplate.
Front Controller – Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.
View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
Dependency injection – Center to the whole BeanFactory / ApplicationContext concepts.
Factory pattern – BeanFactory for creating instance of an object.


Are Singleton beans thread safe in Spring Framework?
No Singleton bean in Spring is not Thread Safe. The two concepts are not even related.

Singletons are about creation. This design pattern ensures that only one instance of a class is created at any point of time. Spring just manage the life cycle of singleton bean and maintains single instance of object.
Thread safety is about execution. Eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe.


How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces.
Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only through.
@Autowired
ServletContext servletContext;

How IOC container will create Object for Private constructor classes?
Answer: Spring internally will use reflection API and it will modify the constructor Accessibility and it will create the object of private constructor class also ,  by using reflection only Spring is doing autowiring and setting the objects into another object.


What are all the AOP advices used in Spring Transaction internally?
Answer: In Spring transaction internally two Advices they used. Before starting the operation it will start the transaction and if operation success it will call commit operation . Here Spring transaction used “Around Advice” and When Saving the Data Error came at that time it  will call rollback operation here they used “throws Advice”


Difference between @Component & @Bean
@Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
@Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.
@Component is a class level annotation where as @Bean is a method level annotation and name of the method serves as the bean name.
@Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
@Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.


Spring Interview Questions - Basic To Advance - Part 1

What is Spring framework?
Spring framework is an open source framework created to solve the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use. Main module for Spring are Spring core,Spring AOP and Spring MVC.

How does spring work internally?
The Spring IoC container
It is the heart of the Spring Framework. The IoC container receives metadata from either an XML file, Java annotations, or Java code. The container gets its instructions on what objects to instantiate, configure, and assemble from simple Plain Old Java Objects (POJO) by reading the configuration metadata provided. These created objects through this process called Spring Beans.

The responsibilities of IoC container are:

Instantiating the bean
Wiring the beans together
Configuring the beans
Managing the bean’s entire life-cycle



This diagram represents an abstract view of the working of the Spring Framework. It shows how Spring makes use of Java POJO classes and configuration metadata.
The real benefits of Spring are showing up through its wiring constructs and using auto-wiring.

Actually by default Spring does not do any bytecode postprocessing neither for XML-, nor annotation-configured beans. Instead relevant beans are wrapped into dynamic proxies (see e.g. java.lang.reflect.Proxy in the Java SDK). Dynamic proxies wrap the actual objects you use and intercept method calls, allowing to apply AOP advices. The difference is that proxies are essentially new artificial classes created by the framework, whereas weaving/bytecode postprocessing changes the existing ones. The latter is impossible without using the Instrumentation API you mentioned.

As for the annotations, the implementation of <context:component-scan> tag will scan the classpath for all classes with the Spring annotations and create Spring metadata placeholders for them. After that they are treated as if they were configured via XML (or to be more specific both are treated the same).

Although Spring doesn't do bytecode postprocessing itself you can configure the AspectJ weaving agent that should work just fine with Spring, if proxies do not satisfy you. Read this for more info.

In a nutshell, if you are not using any @Transactional or any other AOP, proxy will not be created. Spring will directly used the original created object, otherwise ayour class will be wrapped into a proxy and then this proxy will be invoked everytime.

Read this and this.

Explain main modules of Spring ?
Spring AOP:
One of the key components of Spring is the AOP framework. 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
Spring ORM:
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
Spring Web:
The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
Spring DAO:
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
Spring Context:
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
Spring Web MVC:
This is the Module which provides the MVC implementations for the web applications.
Spring Core:
The Core package is the most import component of the Spring Framework.
This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.

What is dependency injection(IOC) in Spring?
The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.



Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones that are actually doing the work.

Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality. Otherwise how will the framework know which components to create if it is no longer in control?

In Java, dependency injection may happen through 3 ways:

A constructor injection
A setter injection
An interface injection

Explain IoC in Spring Framework?
The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container.
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.
IOC Container : Bean Factory & Application Context

Dependency Injection in Spring :

Dependency Injection via Setter method
Setter Injection in Spring is a type of dependency injection in which the framework injects the dependent objects into the client using a setter method. The container first calls the no argument constructor and then calls the setters. The setter based injection can work even If some dependencies have been injected using the constructor.

Setter Injection In spring
EX :
public class Country {

    String countryName;
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}


ApplicationContext.xml

<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
      <property name="countryName" value="India"/>
      <property name="capital" ref="CapitalBean"/>
  </bean>

Dependency Injection via Constructor
 the DI will be injected with the help of contructors. Now to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file.

public class GFG {

    // The object of the interface IGeek
    IGeek geek;

    // Constructor to set the CDI
    GFG(IGeek geek)
    {
        this.geek = geek;
    }
}

<bean id="GFG" class="com.geeksforgeeks.org.GFG">
        <constructor-arg>
            <bean class="com.geeksforgeeks.org.impl.CsvGFG" />
        </constructor-arg>
    </bean>

Setter Dependency Injection (SDI) vs. Constructor Dependency Injection (CDI)
SETTER DICONSTRUCTOR DI
The bean must include getter and setter methods for the properties.The bean class must declare a matching constructor with arguments. Otherwise, BeanCreationException will be thrown.
Circular dependencies or partial dependencies result with Setter DI because object creation happens before the injections.No scope for circular or partial dependency because dependencies are resolved before object creation itself.
Preferred option when properties are less and mutable objects can be created.Preferred option when properties on the bean are more and immutable objects (eg: financial processes) are important for application.
What is Bean in Spring?
A normal POJO class managed by Spring IOC container are called Spring beans. It is core part of Spring application.

How can you configure Spring in your application?

There are 3 ways to do it.

XML based configuration
Java based configuration
Annotation based configuration.

What is Spring XML based configuration?
In Spring XML based configuration, you define all dependency in an XML file. You define all your beans with tag in XML file and all dependencies are read using this XML file.

A Spring XML Configuration uses Spring namespaces to make available the sets of XML tags used in the configuration; the main Spring namespaces are: context, beans, jdbc, tx, aop, mvc, aso.

<beans>

    <!-- JSON Support -->
    <bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
    <bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
   
    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

</beans>

ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

What is Spring java based configuration?
In Spring Java based configuration, you inject all dependencies using java class only. You can use @Configuaration and @Bean annotations to do it.

Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore, @Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class.

The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container. @Bean annotation plays the same role as the <bean/> element.


To enable component scanning, just annotate your @Configuration class as follows:

@Configuration
@ComponentScan(basePackages = "com.howtodoinjava")
public class AppConfig  {
    ...
}

package org.arpit.java2blog.config;
import org.arpit.java2blog.model.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfiguration {

 @Bean(name="countryObj")
 public Country getCountry()
 {
  return new Country("India");
 }

}

Above file is equivalent to below spring configuration xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
 <bean id="countryObj" class="org.arpit.java2blog.Country" >
  <property name="countryName" value="India"/>
 </bean>
</beans>

To get above bean to application context, you need to use below code

ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
 Country countryObj = (Country) appContext.getBean("countryObj");



 What is spring annotation based configuration?
You can do dependency injection via annotation also instead of XML configuration. You can define bean autowiring using annotations. You can use @Component,@Repository,@Service and @Controller annotation to configure bean in Spring application.
Annotations wiring is not turned on by default. You need to turn it on using :

<?xml version="1.0" encoding="UTF-8"?>
<bean>
<context:annotation-config/>
</beans>

Once you put above code, you can start using annotation on class , fields or methods.

Few important annotations which you will be using in this type of configuration are :

@Required : The @Required annotation applies to bean property setter methods.
@Autowired : The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
@Qualifier : The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.


Use this for Complete Java Example.

FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.


How to create ApplicationContext in a Java Program?
There are following ways to create spring context in a standalone java program.

AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.




What are different bean scopes in Spring?
There are 5 types of bean scopes supported in spring

singleton – Scopes a single bean definition to a single object instance per Spring IoC container(per Application Context).
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP session.

 What is default scope of bean in Spring?
singleton is default scope of a bean in Spring. You have to explicitly change scope of a bean if you want different scope.This is one of most asked spring interview questions.

What is ApplicationContext and what are its functions?
ApplicationContext is an central interface for providing configuration information to an application.
An ApplicationContext provides the following functionalities:

Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events. Implementations must provide a means of registering event listeners.
Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

How do you injection collection in Spring?
You can initialize collection using list and value tag as below:

 <bean id="CountryBean" class="org.arpit.java2blog.Country">
  <property name="listOfStates">
   <list>
    <value>Himachal Pradesh</value>
    <value>West Bengal</value>
    <value>Gujrat</value>
   </list>
  </property>
</bean>

What do you mean by bean autowiring in Spring?
In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in .The Spring container can autowire relationships between collaborating beans without using and elements which helps cut down on the amount of XML configuration

<bean id="countryBean" class="org.arpit.java2blog.Country" autowire="byName">

difference between dependency injection and autowiring

Dependency Injection is a design pattern, and @autowired is a mechanism for implementing it.

The DI idea is that, instead of your object creating an object it needs (say by using new to instantiate it), this needed object - a dependency - is handed to your object, typically using the constructor or a setter method. If you autowire, you're injecting a dependancy. In this case, Spring uses reflection to make this work, so you're not using the constructor or a setter method, but you're still injecting the dependency.

Error safe autowiring with ‘required=false’

Even if you have used utmost care in autowiring bean dependencies, still you may find strange lookup failures. So, solve this issue, you will need to make autowiring optional so that if no dependency is found, application should not throw any exception and autowiring should simply be ignored.

This can be done in two ways:

If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.
EmployeeBean.java
@Autowired (required=false)
@Qualifier ("finance")
private DepartmentBean departmentBean;
If you want to apply optional autowiring at global level i.e. for all properties in all beans; use below configuration setting.
beans.xml
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
    <property name="requiredParameterValue" value="false" />

</bean>


Difference between @Autowired , @Resource and @Inject annotation in Spring?

@Autowire , @Inject, @Resource they all server the same purpose

The main difference is that, @Autowired and @Inject works similar for 100% without any differentiation.These two annotations using AutowiredAnnotationBeanPostProcessor to inject dependencies. But,@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies and there is difference in the order of checking.

@Autowired and @Inject

Matches by Type
Restricts by Qualifiers
Matches by Name

@Resource

Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)

The @Inject annotation also serves the same purpose, but the main difference between them is that @Inject is a standard annotation for dependency injection and @Autowired is spring specific


Ref:  https://javabeat.net/difference-resource-autowired-inject-spring-injection/


@Inject and @Named Annotations Difference

JSR-330 annotations.
@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a component/bean.(@Component can be referred from my previous post Classpath Scaning)


What are different modes of autowiring supported by Spring?
There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.
no:
Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via settor method post.
byName:
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file and it tries to match it with name of bean in xml configuration file.
byType:
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
contructor:
byType mode in constructor argument.
autodetect:
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.


@Resource annotation in spring
The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection. Below snippet shows how to use this annotation.



What's the difference between @Component, @Repository & @Service annotations in Spring?

From Spring Documentation:

The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.

Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects.

For example, these stereotype annotations make ideal targets for pointcuts. @Repository, @Service, and @Controller can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

┌──────────────┬─────────────────────────────────────────────────────┐
│ Annotation   │ Meaning                                             │
├──────────────┼─────────────────────────────────────────────────────┤
│  @Component  │ generic stereotype for any Spring-managed component │
│  @Repository │ stereotype for persistence layer                    │
│  @Service    │ stereotype for service layer                        │
│  @Controller │ stereotype for presentation layer (spring-mvc)      │
└──────────────┴─────────────────────────────────────────────────────┘

Sunday, October 20, 2019

Configure Jersey with Annotations only

We need a class that extends the javax.ws.rs.core.Application which will register the jersey application with the help of the @ApplicationPath annotation.

Add jersey dependencies to your classpath.

 <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>


1. We need to extend the javax.ws.rs.core.Application class to configure jersey.
2. We can manually register the rest services by overriding the getClasses() method. But in this example we use a package scanner to automatically pickup rest services in our application. By overriding the getProperties() metod and registering the property
3. jersey.config.server.provider.packages with the packages to search for rest services in our project, jersey is able to automatically register the rest services. Finally we need to map a context path that jersey must listen to. We can achieve this by annotating our class with the @ApplicationPath annotation.

package com.memorynotfound.rs;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class ApplicationConfig extends Application {

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("jersey.config.server.provider.packages", "com.memorynotfound.rs");
        return properties;
    }
}

link : https://memorynotfound.com/configure-jersey-with-annotations-only/

JAX-RS provides the @Context annotation to inject a variety of resources in your RESTful services. Some of the most commonly injected components are HTTP headers, HTTP URI related information.






Exception Handling in Spring MVC

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

@ControllerAdvice
class GlobalDefaultExceptionHandler {
  public static final String DEFAULT_ERROR_VIEW = "error";

  @ExceptionHandler(value = Exception.class)
  public ModelAndView
  defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    // If the exception is annotated with @ResponseStatus rethrow it and let
    // the framework handle it - like the OrderNotFoundException example
    // at the start of this post.
    // AnnotationUtils is a Spring Framework utility class.
    if (AnnotationUtils.findAnnotation
                (e.getClass(), ResponseStatus.class) != null)
      throw e;

    // Otherwise setup and send the user to a default error-view.
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
  }
}

Saturday, October 19, 2019

Difference between JAX-RS and Spring Rest

enter image description here

Examples
Consider the following resource controller using the JAX-RS API:

@Path("/greetings")
public class JaxRsController {

    @GET
    @Path("/{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response greeting(@PathParam("name") String name) {

        String greeting = "Hello " + name;
        return Response.ok(greeting).build();
    }
}
The equivalent implementation using the Spring MVC API would be:

@RestController
@RequestMapping("/greetings")
public class SpringRestController {

    @RequestMapping(method = RequestMethod.GET,
                    value = "/{name}",
                    produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<?> greeting(@PathVariable String name) {

        String greeting = "Hello " + name;
        return new ResponseEntity<>(greeting, HttpStatus.OK);
    }
}

Design Patterns

Categories of Java Design patterns

Creational patterns

Factory method/Template
Abstract Factory
Builder
Prototype
Singleton

Structural patterns

Adapter
Bridge
Filter
Composite
Decorator
Facade
Flyweight
Proxy

Behavioral patterns

Interpreter
Template method/ pattern
Chain of responsibility
Command pattern
Iterator pattern
Strategy pattern
Visitor pattern
Observer design pattern

J2EE patterns

MVC Pattern
Data Access Object pattern
Front controller pattern
Intercepting filter pattern
Transfer object pattern

These design patterns are all about class instantiation or object creation. These patterns can be further categorized into Class-creational patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.

Use case of creational design pattern-
1) Suppose a developer wants to create a simple DBConnection class to connect to a database and wants to access the database at multiple locations from code, generally what developer will do is create an instance of DBConnection class and use it for doing database operations wherever required. Which results in creating multiple connections from the database as each instance of DBConnection class will have a separate connection to the database. In order to deal with it, we create DBConnection class as a singleton class, so that only one instance of DBConnection is created and a single connection is established. Because we can manage DB Connection via one instance so we can control load balance, unnecessary connections, etc.

Use Case Of Structural Design Pattern-

These design patterns are about organizing different classes and objects to form larger structures and provide new functionality.

1) When 2 interfaces are not compatible with each other and want to make establish a relationship between them through an adapter its called adapter design pattern. Adapter pattern converts the interface of a class into another interface or classes the client expects that is adapter lets classes works together that could not otherwise because of incompatibility. so in these type of incompatible scenarios, we can go for the adapter pattern.

Behavioral patterns are about identifying common communication patterns between objects and realize these patterns.
Behavioral patterns are Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Null Object, Observer, State, Strategy, Template method, Visitor

Use Case of Behavioral Design Pattern-

1) Template pattern defines the skeleton of an algorithm in an operation deferring some steps to sub-classes, Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm structure. say for an example in your project you want the behavior of the module can be extended, such that we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications. However, No one is allowed to make source code changes to it. it means you can add but can’t modify the structure in those scenarios a developer can approach template design pattern.

2) Suppose you want to create multiple instances of similar kind and want to achieve loose coupling then you can go for Factory pattern. A class implementing factory design pattern works as a bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as back end, but in future need to change database to oracle, you will need to modify all your code, so as factory design patterns maintain loose coupling and easy implementation we should go for factory for achieving loose coupling and creation of similar kind of object.

Factory Method :

Used to create loosely coupled objects.

Observer design pattern

The Observer Pattern defines a one to many dependency between objects so that one object changes state, all of its dependents are notified and updated automatically.

Suppose we are building a cricket app that notifies viewers about the information such as current score, run rate etc. Suppose we have made two display elements CurrentScoreDisplay and AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the display elements are notified with new data and they display the latest data accordingly


o3

Implementation Link : https://www.geeksforgeeks.org/observer-pattern-set-2-implementation/

Singleton Design Pattern

To be used when only one instance of the class is required,

https://www.geeksforgeeks.org/singleton-design-pattern/

java.lang.Runtime and java.awt.Desktop are 2 singleton classes provided by JVM.

Application  : Cache, ConfigurationFile, DB Classes

How to prevent Singleton Pattern from Reflection, Serialization and Cloning?

Reflection : Use Enum
As enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default constructor, we can’t invoke them by ourself. JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can’t break singleton property in case of enums.

Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method.

  // implement readResolve method
    protected Object readResolve()
    {
        return instance;
    }

Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException.

Decorator Pattern

The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime.
The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.
Decorator offers a pay-as-you-go approach to adding responsibilities. Instead of trying to support all foreseeable features in a complex, customizable class, you can define a simple class and add functionality incrementally with Decorator objects.

https://www.geeksforgeeks.org/decorator-pattern-set-3-coding-the-design/


When to use Strategy Design Pattern in Java?

https://www.geeksforgeeks.org/strategy-pattern-set-2/

One of a good example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface, which is a strategy interface and defines a strategy for comparing objects. Because of this pattern, we don't need to modify sort() method (closed for modification) to compare any object, at the same time we can implement Comparator interface to define new comparing strategy (open for extension).

Facade Design Pattern

So, As the name suggests, it means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. It hides all the complexities of the building and displays a friendly face.

Example : JDBC getConnection();

https://www.geeksforgeeks.org/facade-design-pattern-introduction/


Chain of Responsibility Design Pattern

Chain of Responsibility allows a number of classes to attempt to handle a request, independently of any other object along the chain. Once the request is handled, it completes it’s journey through the chain.

javax.servlet.Filter#doFilter()
The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

java.util.logging.Logger#log
If the logger is currently enabled for the given message level then the given message is forwarded to all the registered output Handler objects.

Adapter Design Pattern in Java

Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter input: " + s);
Now observe above code carefully.

1) System.in is static instance of InputStream declared as:

public final static InputStream in = nullInputStream();
This input stream reads the data from console in bytes stream.

2) BufferedReader as java docs define, reads a character stream.

//Reads text from a character-input stream, buffering characters so as to
//provide for the efficient reading of characters, arrays, and lines.

public class BufferedReader extends Reader{..}
Now here is the problem. System.in provides byte stream where BufferedReader expects character stream. How they will work together?

This is the ideal situation to put a adapter in between two incompatible interfaces. InputStreamReader does exactly this thing and works adapter between System.in and BufferedReader.

/** An InputStreamReader is a bridge from byte streams to character streams:
  * It reads bytes and decodes them into characters using a specified charset.
  * The charset that it uses may be specified by name or may be given explicitly,
  * or the platform's default charset may be accepted.
  */

public class InputStreamReader extends Reader {...}


1) java.util.Arrays#asList()

This method accepts multiple strings and return a list of input strings. Though it’s very basic usage, but it’s what a adapter does, right?

2) java.io.OutputStreamWriter(OutputStream)

It’s similar to above usecase we discussed in this post:

Writer writer = new OutputStreamWriter(new FileOutputStream("c:\\data\\output.txt"));
writer.write("Hello World");
3) javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()

Adapts a Java type for custom marshaling. Convert a bound type to a value type.