What is difference between singleton and prototype bean?

  • Singleton Bean – a single object instance per Spring IOC container
  • Prototype Bean – any number of object instances per Spring IOC Container

What is AutoProxying?

Autoproxying is used to create proxies automatically for the spring beans. Spring comes with two auto proxy creators to create proxies for beans automatically:

  • BeanNameAutoProxyCreator
  • DefaultAdvisorAutoProxyCreator

What are the different types of AutoProxying in spring framework?

Different types of AutoProxying are shown below:

  • BeanNameAutoProxyCreator – identifies beans to proxy via a list of names. automatically creates AOP proxies for beans with names matching literal values or wildcards
  • DefaultAdvisorAutoProxyCreator – automagically applies eligible advisors in the current context without the need to include specific bean names in the auto-proxy advisor’s bean definition
  • Metadata autoproxying – autoproxying driven by metadata. for example, transaction management

What is the drawback of inner bean?

Drawback of inner bean is that it cannot be reprocessed.

Explain the term Proxy?

The term proxy refers to an object which is produced in the application of an advice to the target object.

What is spring’s @Qualifier annotation?

The qualifier annotation helps disambiguate bean references when spring would otherwise not be able to do so.
Please refer to the example https://spring.io/blog/2014/11/04/a-quality-qualifier for more information on it.

How is bean’s life cycle maintained?

A bean is required to be instantiated by spring container before its usage. Similarly, the bean is removed by the spring container when it is no longer in use.

Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans consist of callback methods which can be categorized broadly in two groups:

  • Post initialization callback methods
  • Pre destruction callback methods

Spring framework provides following four ways for controlling life cycle events of beans:

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

For example, beanInit() and beanDestroy() methods are example of life cycle method:

<beans>
    <bean id="demoBean" class="com.roytuts.beans.InitDestroyDemoBean"
            init-method="beanInit" destroy-method="beanDestroy"></bean>
</beans>

What is @Required annotation?

There might be a situation in a large-scale application where a bean might have hunderds or more attributes that are again spring beans declared in the IoC container and dependencies between them are very complicated. You may not be able check whether all required attributes are set or not using setter injection. So to check if a particulat set of attributes have been set or not, you can use @Required annotation over setter method of bean property in a class.

If any properties with @Required have not been set, a BeanInitializationException will be thrown by this bean post processor.

To enable this bean post-processor for property checking, you must register it in the spring IoC container by declaring the following bean.

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

How to make a bean as singleton in spring ?

Singleton scope in Spring means that this bean will be instantiated only once by Spring. In contrast to the prototype scope (new instance each time), request scope (once per request), session scope (once per HTTP session). The scope of a Spring singleton is described as “per container per bean”. It is the scope of bean definition to a single object instance per Spring IoC container. The default scope for a bean in Spring is Singleton.

What is IOC or inversion of control ?

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.

IOC means Inversion of Control that is known as Dependency Injection(DI), a process whereby objects define their dependencies. How these dependencies are defined – objects work with other objects that are defined only through constructor arguments, arguments to a factory method, or properties that are set on the object instance which is constructed or returned from a factory method. The Spring container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC) – the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans.

For more information please read http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html

How does Spring container instantiate beans ?

The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans.

The configuration metadata such as objects that compose your application and interdependencies between objects are represented in XML, Java annotations, or Java code. Spring container then gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.

In XML-based configuration metadata, you specify the type (or class) of object that is to be instantiated in the class attribute of the <bean/> element. This class attribute, which internally is a Class property on a BeanDefinition instance, is usually mandatory.

Class property of <bean/> can be use in one of two ways:

To specify the bean class to be constructed where the container itself directly creates the bean by calling its constructor reflectively, somewhat equivalent to Java code using the new operator.

To specify the actual class containing the static factory method that will be invoked by the container to create the object. The object type returned from the invocation of the static factory method may be the same class or another class entirely.

What implementations for interface org.springframework.context.ApplicationContext are provided by Spring ?

Spring provides two implementations out-of-the-box – ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.

So, in standalone application we have to read the configuration metadata file by creating new instance either of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.

How to read configuration metadata file in Spring stand-alone application ?

Create a POJO class

package com.roytuts.spring.di;

public class SetterInjectionExample {

    private String message = null;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Define XML configuration metadata – applicationContext.xml and put it under classpath (src/main/resources)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                              http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="messageSI"
          class="com.roytuts.spring.di.SetterInjectionExample">
        <property name="message" value="Setter Injection in Spring" />
    </bean>

</beans>

Read configuration metadata

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

or

ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");

Get instance of the bean

SetterInjectionExample setterInjectionExample = (SetterInjectionExample) applicationContext.getBean("messageSI");

or

SetterInjectionExample setterInjectionExample = applicationContext.getBean("messageSI", SetterInjectionExample);

How to read configuration metadata file in Spring web application ?

Suppose you have above POJO and applicationContext.xml file under WEB-INF directory, then you can read it using web.xml file easily

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

The listener inspects the contextConfigLocation parameter. If the parameter does not exist, the listener uses /WEB-INF/applicationContext.xml as a default. When the parameter does exist, the listener separates the String by using predefined delimiters (comma, semicolon and whitespace) and uses the values as locations where application contexts will be searched. Ant-style path patterns are supported as well. Examples are /WEB-INF/*Context.xml for all files with names ending with “Context.xml”, residing in the “WEB-INF” directory, and /WEB-INF/**/*Context.xml, for all such files in any subdirectory of “WEB-INF”.

How to load multiple XML configuration files in Spring ?

When you have multiple XML configuration files segregated based on modules or logical layer then you can use the application context constructor to load bean definitions from all these XML fragments as shown below.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml", "datasource.xml", "dao.xml", "resources/messageSource.xml"});

Alternatively, use one or more occurrences of the <import/> element to load bean definitions from another file or files.

<beans>
    <import resource="datasource.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="dao.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>

In the example above, external bean definitions are loaded from three files: datasource.xml, messageSource.xml, and dao.xml. All location paths are relative to the definition file doing the importing, so datasource.xml and dao.xml must be in the same directory or classpath location as the file doing the importing, while messageSource.xml must be in a resources location below the location of the importing file.

What is bean in Spring ?

Every Java class in Spring is eventually called a bean. So all beans are managed by Spring IoC container that creates by reading the configuration metadata. In Spring container the bean is represented as BeanDefinition object which contains several information along with the following important information:

i. A full package-qualified actual implementation class name is defined as bean
ii. The scope of the bean in the container like request, singleton, prototype, session etc.
iii. References (if any) to other beans that are needed for the beans to do its work. These references are called collaborators or dependencies.
iv. Other configurations of the bean, for example, the number of connections to use in a bean that manages a connection pool, or the size limit of the pool.
v. Other important configurations like whether the bean would be loaded lazily, whether there is any initialization works need to be performed after container has created the bean instance.

How do you name a bean in Spring ?

Every bean has one or more identifiers. These identifiers must be unique within the container that defines the bean. A bean usually has only one identifier, but if it requires more than one, the extra ones can be considered aliases.

In XML based configuration you usually use id for identifier and it must be unique per container. You can also use name as other aliases for the bean. If you want to give multiple names for a bean then you have to separate them in the name attribute by comma(,), semicolon(;), or whitespace. The bean id or name value can contain alphanumeric meaningful name, it may also contain some special characters.

How to instantiate a bean with a static factory method in Spring ?

When defining a bean using <bean/> tag in XML configuration metadata, we use class attribute to specify the class and factory-method attribute to specify the name of the factory-method the class contains itself.

One use for such a bean definition is to call static factories in legacy code.

Example,

Create a POJO class

package com.roytuts.spring.di;

public class StaticFactoryExample {

    private static StaticFactoryExample staticFactoryExample = new StaticFactoryExample();
    
    private StaticFactoryExample() {}

    public static StaticFactoryExample createInstance() {
        return staticFactoryExample;
    }

}

Define XML configuration metadata – applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                              http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="staticFactory"
          class="com.roytuts.spring.di.StaticFactoryExample" factory-method="createInstance">
    </bean>

</beans>