Spring :
- It is open source enterprise development application framework.
- It provides container to create and manage objects and also provide enterprise service to those object
- It is primary based on IOC and DI design pattern
- It provides the ready component for different tier of application eg : web,data access,business and middle tier
- Layered Architecture
Why Spring :
- Light Weight
- IOC
- AOP
- Container
- Framework
Inverse of control and Dependency Injection :
- It is design pattern.
- It is used to give control to the assembler of classes
Example :
Generally, if a class wants to use another class, it instantiates desired class. But using this design pattern, the instantiation control is provided to the assembler. Assembler instantiates the required class and injects it in using class
Different Type of DI / IOC :
- Setter Injection
- Constructor Injection
- Interface Injection
Different Modules in Spring :
- Spring Core
- Spring Context
- Spring web
- Spring web MVC
- Spring ORM
- Spring DAO
- Spring AOP
IOC container in Spring :
- Instantiates the Object
- Inject the object in each other
- Provide enterprise service [Ex : AOP and Transaction Management] to those object
BeanFactory Interface :
1. It provides configuration framework for object creation and basic functionality around object management
ApplicationContext Interface :
- It is build around Spring’s BeanFactory
- It provides enterprise centeric features eg AOP, message resouring, event propogating and application-layer-specific context to application
Difference Between BeanFactory and ApplicationContext :
- BeanFactory is used for core configution and provide basic centric functionality to application
- ApplicationContext provides enterprise centric functionality to application
What is your preference BeanFactory or ApplicationContext? Why?
ApplicationContext. It provides all features provided by BeanFactory and enterprise centric more features, which may be required by application in future
How to instantiates the IOC container ?
Common Implementation of ApplicationContext:
- classPathXmlApplicationContext
- fileSystemXmlApplicationContext
- xmlWebApplicationContext
ex :
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
How does a web application use Spring’s configuration xmls?
1. Spring container/configuration xmls can be integrated with web application through web.xml
Following entries in web.xml can integrate Spring container with web container.
<context-param> <description> Context parameter to integrate Spring and Web containers </description> <param-name>contextConfigLocation</param-name> <param-value> classpath: services.xml,classpath: daos.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
How to integrate multiple bean configuration xmls?
Multiple bean configuration xmls are created to separate configurations according to layers so that it becomes easy to manage and maintain them. These configuration xmls can be imported in single xml to combine all of them.
<beans> <import resource="services.xml"/> <import resource="daos.xml"/> <bean id="bean1"/> <bean id="bean2"/> </beans>
Lazily-instantiated beans :
1. By default Spring instantiates a singleton beans at the time of startup [Eagerly Instantiation]
This is good behavior as it exposes any problems in instantiation of beans at start up only. But sometimes this behavior is not expected hence by addition lazy-init=”true” to the bean definition the instantiation can be postponed to first request. Also following configuration will not allow any bean to get instantiated
eagerly.
<beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> </beans>
Autowiring :
- By Autowiring , Spring injects dependencies without having to specify those explicitly.
- Spring inspects bean factory contents and establishes relationships amongst collaborating beans. To implement it,just add autowire property in xml configuration.
Different Modes of autowiring :
Autowiring having five following modes:
- no : no autowire
- byName : Autowiring by property name, means bean matching property name is autowired.
- byType : Bean having type as that of property type is autowired.
- constructor : Similar to byType just that the property is in constructor.
- autodetect : Spring is allowed to select autowiring from byType and constructor
Different bean scopes available to configure :
- singleton : One bean instance per IoC container [It is default]
- prototype : Any number of instances of bean
- request : Within HTTPRequest object scope
- session : As long as HttpSession is alive
- globalsession : Within life-cycle of global HttpSession. Applicable in portlet context usually.
How can you control bean instantiation process?
1. Bean Initailization by spring can be controlled by using initialization call backs.
There are two ways to do it.
- First is having a initialization method (say init()) and specifying it in bean configuration as ‘init-method’ property
- Second is implementing InitializingBean interface and implementing afterPropertiesSet() method in it.
How can you control bean destruction process?
There are two ways to do it.
- First is add a destroy() method and specify it in bean configuration as ‘destroy-method’ property
- Second is implement DisposableBean interface and implement destroy() method of it.
What all you have to do to start using Spring?
- Download Spring (and dependent Jars) from Spring’s site.
- Create application context xml to define beans and dependencies.
- Integrate this xml with web.xml
- Deploy and Run the application
Design Patterns are used in Spring:
- Factory Pattern : BeanFactory for creating instance of an object Singleton : instance type can be singleton for a context Prototype : instance type can be prototype.
- Abstract Factory Pattern
- Builder Pattern : you can also define a method in a class who will be responsible for creating complex instance.
- Decorator Pattern
- Service Locator
- Proxy – used heavily in AOP, and remoting.
- Singleton – beans defined in spring config files are singletons by default.
- Model View Controller :The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers for different view technologies.
- 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.
Implement Inheritence in Bean Definition :
Inheritence can be implement to specifying the ‘parent’ property in bean and pass id of (parent) bean.
Bean Life Cycle in spring container:
- Spring container finds the bean definition from xml configuration file and instataite the bean.
- Using the DI,Spring populate all the properies specified in bean definition.
- If the bean implements the BeanNameAware interface ,then factory calls the setBeanName() and pass id in it.
- If the bean implements the BeanFactoryAware interface , then factory call the setBeanFactory and pass bean instance 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 are singleton beans and how can you create prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named “singleton” if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default
it is set to true. So, all the beans in spring framework are by default singleton beans.
<beans> <bean id="bar" singleton="false"/> </beans>
What are the important beans lifecycle methods?
There are the two important beans lifecycle method.
1. setup
2. teardown
setup – it is called when bean is loaded into the container
teardown – it is called when bean is unloaded from the container
How can you override beans default lifecycle methods?
The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods.
Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.
<beans> <bean id="bar" init-method="fooSetup" destroy="fooTeardown"/> </beans>
Inner Bean in Spring :
When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.
Example :
In Spring framework, whenever a bean is used for only one particular property, it’s advise to declare it as an inner bean.And the inner bean is supported both in setter injection ‘property‘ and constructor injection
‘constructor-arg‘.
public class Customer
{
private Person person;
public Customer(Person person) {
this.person = person;
}
public void setPerson(Person person) {
this.person = person;
}
@Override
public String toString() {
return "Customer [person=" + person + "]";
}
}
public class Person
{
private String name;
private String address;
private int age;
//getter and setter methods
@Override
public String toString() {
return "Person [address=" + address + ",
age=" + age + ", name=" + name + "]";
}
}
Often times, you may use “ref” attribute to reference the “Person” bean into “Customer” bean, person property as following :
<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-2.5.xsd"> <bean id="CustomerBean"> <property name="person" ref="PersonBean" /> </bean> <bean id="PersonBean"> <property name="name" value="mkyong" /> <property name="address" value="address1" /> <property name="age" value="28" /> </bean> </beans>
In general, it’s fine to reference like this, but since the ‘mkyong’ person bean is only used for Customer bean only, it’s better to declare this ‘mkyong’ person as an inner bean as following :
<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-2.5.xsd"> <bean id="CustomerBean"> <property name="person"> <bean> <property name="name" value="mkyong" /> <property name="address" value="address1" /> <property name="age" value="28" /> </bean> </property> </bean> </beans>
This inner bean also supported in constructor injection as following :
<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-2.5.xsd"> <bean id="CustomerBean"> <constructor-arg> <bean> <property name="name" value="mkyong" /> <property name="address" value="address1" /> <property name="age" value="28" /> </bean> </constructor-arg> </bean> </beans>
Run It :
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
What are the different types of events related to Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.springframework.context.Application-Event.
They are :
- ContextClosedEvent – This is fired when the context is closed.
- ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
- RequestHandledEvent – This is fired when the web context handles any request.
DataAccessException :
- It is runtime/unchecked exception. [User can not be froced to handle this type of exception]
- Spring DAO is not throws any technology specific exception like SQLException . it is throw a subtype of dataaccess exception
Configure a bean to get DataSource from JNDI?
<bean id="dataSource"> <property name="jndiName"> <value>java:comp/env/jdbc/myDatasource</value> </property> </bean>
Create a DataSource connection pool?
<bean id="dataSource">
<property name="driver">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
What are the types of the transaction management Spring supports ?
- declarative
- programatically
Spring Programatically transaction management Example :
<?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-3.0.xsd "> <!-- Initialization for data source --> <bean id="dataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/TEST"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean> <!-- Initialization for TransactionManager --> <bean id="transactionManager" > <property name="dataSource" ref="dataSource" /> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id="studentJDBCTemplate" > <property name="dataSource" ref="dataSource" /> <property name="transactionManager" ref="transactionManager" /> </bean> </beans>
You can free to add more questions in comment for readers.
Thanks to visit aoiblog.com

