What is Spring?
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
What are benefits of using spring?
Following is the list of few of the great benefits of using Spring Framework:
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
What are the different modules in Spring framework?
Following are the modules of the Spring framework:
- Core module
- Bean module
- Context module
- Expression Language module
- JDBC module
- ORM module
- OXM module
- Java Messaging Service(JMS) module
- Transaction module
- Web module
- Web-Servlet module
- Web-Struts module
- Web-Portlet module
What is Spring configuration file?
Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.
What is Dependency Injection?
Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.
This concept says 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 (the IOC container) is then responsible for hooking it all up.
What are the different types of IOC (dependency injection) ?
There are three types of dependency injection:
Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection
What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
- Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
- Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
- Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
- IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.
What are types of IoC containers? Explain them.
There are two types of IoC containers:
Bean Factory container:This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
Spring ApplicationContext Container:This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
What is Bean Factory ?
BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
- BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
- BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
What is Application Context?
A Bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
- A means for resolving text messages, including support for internationalization.
- A generic way to load file resources.
- Events to beans that are registered as listeners.
What is the difference between Bean Factory and Application Context ?
On the surface, an application context is same as a bean factory. But application context offers much more.
- Application contexts provide a means for resolving text messages, including support for i18n of those messages.
- Application contexts provide a generic way to load file resources, such as images.
- Application contexts can publish events to beans that are registered as listeners.
- Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
- ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
- MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
Give an example of BeanFactory implementation.
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.
What are the common implementations of the ApplicationContext?
The three commonly used implementation of ‘Application Context’ are:
FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
: This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.
What are Spring beans?
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML
What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
- The spring container finds the bean’s definition from the XML file and instantiates the bean.
- Using the dependency injection, spring populates all of the properties as specified in the bean definition
- If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
- If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
- If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
- If an init-method is specified for the bean, it will be called.
- Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
What bean scopes does Spring support? Explain them.
The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.
singleton: This scopes the bean definition to a single instance per Spring IoC container.
prototype: This scopes a single bean definition to have any number of object instances.
request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
What is default scope of bean in Spring framework?
The default scope of bean is Singleton for Spring framework.
Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.
How can you inject Java Collection in Spring?
Spring offers four types of collection configuration elements which are as follows:
list: This helps in wiring i.e. injecting a list of values, allowing duplicates.
set: This helps in wiring a set of values but without any duplicates.
map: This can be used to inject a collection of name-value pairs where name and value can be of any type.
props: This 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 your bean by inspecting the contents of the BeanFactory without using
What are 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 which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
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. It then tries to match and wire its properties with the beans defined by the same names in the 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 exist, a fatal exception is thrown.
constructor: 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.
What are the limitations with autowiring?
Limitations of autowiring are:
Overriding possibility: You can still specify dependencies using
and settings which will always override autowiring.
Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
Can you inject null and empty string values in Spring?
What is Annotation-based container configuration?
An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
How do you turn on annotation wiring?
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring
What does @Required annotation mean?
This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.
What does @Autowired annotation mean?
This annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
What does @Qualifier annotation mean?
There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.
What are the JSR-250 Annotations? Explain them.
Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.
@PostConstruct:This annotation can be used as an alternate of initialization callback.
@PreDestroy:This annotation can be used as an alternate of destruction callback.
@Resource:This annotation can be used on fields or setter methods. The @Resource annotation takes a ‘name’ attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.
What is Spring Java Based Configuration? Give some annotation example.
Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations.
For example: Annotation
@Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The
@Bean annotation tells Spring that a method annotated with
@Bean will return an object that should be registered as a bean in the Spring application context.
How is event handling done in Spring?
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.
What are the standard Spring events.
Spring provides the following 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 housekeep 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.
What are 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
Aspect Oriented Programming