Spring Core

What is Spring ?

The Spring Framework is an open source application framework and inversion of control container for the Java platform. The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application. The Spring Framework is a lightweight solution and a potential one-stop-shop for building your enterprise-ready applications. Spring is modular, allowing you to use only those parts that you need, without having to bring in the rest.

What are modules available in Spring framework ?

The Spring Framework consists of features organized into about 20 modules. These modules are grouped into seven main modules such as Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test.

Core Container modules contains Beans, Core, Context and SpEl(Spring Expression Language).

Data Access/Integration contains JDBC, ORM, OXM(Object/XML mapping), JMS and Transaction.

Web module contains WebSocket, Servlet, Web and Portlet.

What are new features in Spring version 4 ?

This is the latest major release of the Spring Framework and the first to fully support Java 8 features.

All deprecated packages, and many deprecated classes and methods have been removed with this version. For information please read http://docs.spring.io/spring-framework/docs/3.2.4.RELEASE_to_4.0.0.RELEASE/

Spring 4 requires the recent Hibernate Validator 4.3+, and support for Jackson has been focused on 2.0+.

Java 8’s features such as lambda expression and method references can be used in Spring’s callback interfaces.

Java 8’s parameter name discovery (based on the -parameters compiler flag) can be used as an alternative to compiling the source code with debug information enabled.

Java EE version 6 or above is now considered as the baseline for Spring Framework 4, with the JPA 2.0 and Servlet 3.0+ is strongly recommended.

Beans can now be ordered when they are autowired into lists and arrays. Both the @Order annotation and Ordered interface are supported.

The @Lazy annotation can now be used on injection points, as well as on @Bean definitions.

The @Description annotation has been introduced for developers using Java-based configuration.

CGLIB-based proxy classes no longer require a default constructor. Support is provided via the objenesis library which is repackaged inline and distributed as part of the Spring Framework. With this strategy, no constructor at all is being invoked for proxy instances anymore.

There is managed time zone support across the framework now, e.g. on LocaleContext.

The new @RestController annotation can be used with Spring MVC applications, removing the need to add @ResponseBody to each of @RequestMapping methods.

The AsyncRestTemplate class has been added, allowing non-blocking asynchronous support when developing REST clients.

Spring now offers comprehensive timezone support when developing Spring MVC applications.

Almost all annotations in the spring-test module (e.g., @ContextConfiguration, @WebAppConfiguration, @ContextHierarchy, @ActiveProfiles, etc.) can now be used as meta-annotations to create custom composed annotations and reduce configuration duplication across a test suite.

Active bean definition profiles can now be resolved programmatically, simply by implementing a custom ActiveProfilesResolver and registering it via the resolver attribute of @ActiveProfiles.

A new SocketUtils class has been introduced in the spring-core module which enables to scan for free TCP and UDP server ports on localhost. This functionality is not specific to testing but can prove very useful when writing integration tests that require the use of sockets, for example tests that start an in-memory SMTP server, FTP server, Servlet container, etc.

Message listener endpoints have now more flexible signature and can benefit from standard messaging annotations such as @Payload, @Header, @Headers, and @SendTo. It is also possible to use a standard Message in lieu of javax.jms.Message as method argument.

A new JmsMessageOperations interface is available and permits JmsTemplate like operations using the Message abstraction.

Synchronous request-reply operations support in JmsTemplate.

Listener priority can be specified per <jms:listener/> element.

Recovery options for the message listener container are configurable using a BackOff implementation.

JMS 2.0 shared consumers are supported.

Caches can be resolved at runtime using a CacheResolver. So value argument defining the cache name is no longer required to use.

More operation-level customizations: cache resolver, cache manager, key generator.

A new @CacheConfig class-level annotation allows common settings to be shared at the class level without enabling any cache operation.

Better exception handling of cached methods using CacheErrorHandler.

There are many more improvements, you can read here http://docs.spring.io/spring/docs/current/spring-framework-reference/html/new-in-4.1.html

Why spring framework seems to be needed?
Spring framework seems to be needed because of following important features

  • Very Light Weight Container
  • Framework
  • IOC
  • AOP

What are the benefits of spring framework?
Spring framework provides following benefits

  • Extensive usage of Components
  • Reusability
  • Decoupling/Loose-coupling
  • Reduces coding effort by using pattern implementations such as singleton, factory, service locator, template etc.
  • Removal of leaking connections
  • Declarative transaction management
  • Easy to integrate with third party tools and technologies

What is Dependency Injection ?

A Java application that runs a variety of applications like constrained, embedded applications, server-side enterprise applications etc. and these applications typically consist of several objects that collaborate to each other properly. Thus objects in an application have dependencies on each other.

For more information please read https://roytuts.com/what-is-dependency-injection/

What are the different types of dependency injections in spring ?

There are three types of dependency injections and they are constructor injection, setter injection and interface injection.

Spring supports only constructor and setter injection. Interface injection is supported by other language like Avalon. It’s a different type of DI(dependency injection) that involves mapping items to inject to specific interfaces.

Spring supports Setter Injection via JavaBean setters; and Constructor Injection via constructor arguments.

Constructor Injection

package com.roytuts.spring.di;
public class ConstructorInjectionExample {
    private String message = null;
    /**
     * Constructor
     */
    public ConstructorInjectionExample(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

Spring configuration file

The constructor-arg element injects a message into the bean using the constructor-arg element’s value attribute.

<?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="messageCI"
          class="com.roytuts.spring.di.ConstructorInjectionExample">
        <constructor-arg value="Constructor Injection in Spring" />
    </bean>
</beans>

Setter Injection

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;
    }
}

Spring configuration file

The property element is used to define the setter injection.

<?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>

Are Singleton beans thread-safe in spring framework?

No. If you want to make singleton bean thread-safe then you have apply Java’s synchronization mechanism.

What is BeanFactory in Spring ?

BeanFactory is the root interface for accessing a Spring bean container. This interface is implemented by objects that hold a number of bean definitions, each uniquely identified by a String name. Depending on the bean definition, the factory will return either an independent instance of a contained object (the Prototype design pattern), or a single shared instance (a superior alternative to the Singleton design pattern, in which the instance is a singleton in the scope of the factory). Which type of instance will be returned depends on the bean factory configuration. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory.

The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications where memory consumption might be critical, and a few extra kilobytes might make a difference.

There are three ways to configure BeanFactory.

Resource resource = new FileSystemResource("spring-beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(resource);
ClassPathResource classPathResource = new ClassPathResource("spring-beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(classPathResource);
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
BeanFactory factory = (BeanFactory) applicationContext;
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "spring-beans.xml", "spring-datasource.xml"});
BeanFactory factory = (BeanFactory) applicationContext;

7. What is difference between BeanFactory and ApplicationContext in spring ?

i. BeanFactory instantiate bean when you call getBean() method while ApplicationContext instantiate Singleton bean when container is started, it does not wait for getBean() to be called.

ii. BeanFactory does not provide support for internationalization of MessageSource but ApplicationContext provides support for MessageSource in i18n style.

iii. Another difference between BeanFactory and ApplicationContext is the ability to publish event to beans that implement the ApplicationListener interface.

iv. XMLBeanFactory class is the popular implementation of BeanFactory interface whereas ClassPathXmlApplicationContext is the popular implementation of ApplicationContext interface.

v. ApplicationContext has support for Automatic BeanPostProcessor and BeanFactoryPostProcessor registration but BeanFactory does not have.

For more information please read http://docs.spring.io/spring/docs/2.5.x/reference/beans.html#context-introduction-ctx-vs-beanfactory

What is bean wiring?

Bean wiring is the creation of association between application components that are actually beans in spring container.

List down different modes of auto-wiring in spring framework

autodetect :  Spring is allowed to select autowiring from byType or constructor

Tell me the name of the methods of bean’s life cycle

There are two important methods of Bean life cycle:

  • Setup – called when bean is loaded into the container
  • Teardown – called when bean is unloaded from the container

What are the different types of events registered as listeners in spring framework?

There are three types of events registered as listeners as given below:

  • ContextClosedEvent – called when the context is closed
  • ContextRefreshedEvent – called when context is initialized or refreshed
  • RequestHandledEvent – called when the web context handles request