Tuesday, March 1, 2011

Spring – InitializingBean and DisposableBean


Spring – InitializingBean and DisposableBean 

In Spring, InitializingBean and DisposableBean are two interfaces, implementing these interfaces will make Spring calling afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction.
Here’s an example to show how to use InitializingBean and DisposableBean.
in Spring, it’s encouraged to use init-method=”method name” and destroy-method=”method name” as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction.

Spring – Properties dependency checking


Spring – Properties dependency checking

In Spring framework, you can make sure all the required properties have been set in bean by using properties dependency checking feature.

Dependency checking modes

In Spring, 4 dependency checking modes are supported:
  • none – No dependency checking.
  • simple – If any properties of primitive type (int, long,double…) and collection types (map, list..) have not been set, UnsatisfiedDependencyException will be thrown.
  • objects – If any properties of object type have not been set, UnsatisfiedDependencyException will be thrown.
  • all – If any properties of any type have not been set, an UnsatisfiedDependencyException
    will be thrown.

How to integrate your Struts application with Spring


How to integrate your Struts application with Spring
To integrate your Struts application with Spring, we have two options:
1.      Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
2.      Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext()method.

Procedure to integrate struts and spring according to case 1
1.      get and include the “struts2-spring-plugin-xxx.jar
2.      Configure the Spring listener “org.springframework.web.context.ContextLoaderListener” in web.xml file.
               <listener>
                        <listener-class>
                                       org.springframework.web.context.ContextLoaderListener
                         </listener-class>
            </listener>
3.      Register all the Spring’s Beans in the applicationContext.xml file; the Spring listener will locate this xml file automatically.
               <bean id="userBo" class="com.mkyong.user.bo.impl.UserBoImpl" />
            <bean id="userSpringAction" class="com.mkyong.user.action.UserSpringAction">
                        <property name="userBo" ref="userBo" />            
            </bean>
4.      Declared all the relationship in struts.xml
               <action name="userSpringAction"  class="userSpringAction" >
                        <result name="success">pages/user.jsp</result>
            </action>
  This will pass the Spring’s “userBo” bean into the UserAction via setUserBo() automatically.
            UserBo userBo; 
            public void setUserBo(UserBo userBo) {
                        this.userBo = userBo;
Alternatively, you can use the Spring’s generic WebApplicationContextUtils class to get the Spring’s bean directly.
WebApplicationContext context =
                                     WebApplicationContextUtils.getRequiredWebApplicationContext(
                                    ServletActionContext.getServletContext()
                        );
                        UserBo userBo1 = (UserBo)context.getBean("userBo");
                        userBo1.printUser ();

How to integrate Spring and Hibernate using HibernateDaoSupport


What are the ways to access Hibernate using Spring
There are two approaches to spring’s Hibernate integration:
1.      Inversion of Control with a HibernateTemplate and Callback
2.      Extending HibernateDaoSupport and Applying an AOP Interceptor

How to integrate Spring and Hibernate using HibernateDaoSupport case 2
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
  • Configure the Hibernate SessionFactory
  • Extend your DAO Implementation from HibernateDaoSupport
  • Wire in Transaction Support with AOP
1. mapping with the table in the .hbm.xml file
2. <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/ims"/>
              <property name="username" value="root"/>
              <property name="password" value="root"/>                  
     </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
                               <value>/po/users.hbm.xml</value>
            <value>/po/messages.hbm.xml</value>
            <value>/po/keywords.hbm.xml</value>
            <value>/po/pastsessioninfo.hbm.xml</value>
                  </list>
             </property>
            <property name="hibernateProperties" value="hibernate.dialect=org.hibernate.dialect.MySQLDialect"/>
     </bean>
3. the dao class should implement HibernateDaoSupport 

What do you mean by Auto Wiring


What do you mean by Auto Wiring
The Spring container is able to auto wire relationships between collaborating beans. This means that it is possible to automatically let Spring collaborate your beans by inspecting the contents of the BeanFactory. The auto wiring functionality has five modes.
  • no – No auto-wiring. This is the default mode; you have to wire your bean explicitly by using the ‘ref’ attribute.
  • byName – Auto-wire a bean whose name is same as the property.
  • byType – Auto-wire a bean whose data type is compatible with the property. The problem is sometimes there will be more than one beans are match with ‘byType’ criteria. In this case, Spring will throw an UnsatisfiedDependencyException exception.
  • constructor – Auto-wire a bean whose date type is compatible with the property constructor argument. The ‘constructor’ mode is facing the same problem with ‘byType’ auto-wire mode
  • autodetect – If a default constructor with no argument is found, it will auto-wire by data type. Otherwise, it will auto-wire by constructor. It has the same problem with ‘byType’ and ‘constructor’,
It’s always good to combine the ‘auto-wire’ and ‘dependency-check’ feature together to make sure the property is auto-wire successfully.
e.g.      <bean id="CustomerBean" class="com.mkyong.common.Customer" 
                                    autowire="autodetect" dependency-check="objects">
                    <property name="action" value="buy" />
                    <property name="type" value="1" />
           </bean>
           <bean id="PersonBean" class="com.mkyong.common.Person">
                    <property name="name" value="mkyong" />
                    <property name="address" value="address 123" />
                    <property name="age" value="28" />
            </bean>

What is the typical Bean life cycle in Spring Bean Factory Container


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(String name) ,It sets the name of the bean in the bean factory that created this bean.
·   If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(BeanFactory beanFactory), passing an instance of itself. Invoked after the population of normal bean properties but before an initialization callback such as InitializingBean.afterPropertiesSet() or a custom init-method.
·   If the bean implements the BeanPostProcessors interface, their postProcessBeforeInitialization(Object bean, String beanname) methods will be called.
·   If an init-method is specified for the bean, it will be called.
·   If the bean implements the BeanPostProcessors interface, their postProcessAfterInitialization (Object bean, String beanname) methods will be called.

Monday, February 28, 2011

How is a typical spring implementation look like


How is a typical spring implementation look like
For a typical Spring Application we need the following files:
·   An interface that defines the functions.
·   An Implementation that contains properties, its setter and getter methods, functions etc.,
·   Spring AOP (Aspect Oriented Programming)
·   A XML file called Spring configuration file.
·   Client program that uses the function.

What are the common implementations of the Application Context


What are the common implementations of the Application Context
The three commonly used implementation of 'Application Context' are
·   ClassPathXmlApplicationContext: It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code.
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
·   FileSystemXmlApplicationContext: It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code.
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
·   XmlWebApplicationContext: It loads context definition from an XML file contained within a web application.

What is Application Context


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 support for internationalization.
·   A generic way to load file resources.
·   Publish events to beans that are registered as listeners.

What is Bean Factory


What is Bean Factory
A 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.

How many modules are there in Spring? What are they?


 How many modules are there in Spring? What are they?
Spring comprises of seven modules. They are.
·   The core container:
The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.
·   Spring context:
The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
·   Spring AOP:
Spring supports Aspect oriented programming which enables us to perform some desired action just before or after the execution of the specified method
·   Spring DAO:
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring Dao’s JDBC-oriented exceptions comply with its generic DAO exception hierarchy.
·   Spring ORM:
Spring provides best Integration services with Hibernate which comply with Spring's generic transaction and DAO exception hierarchies.
·   Spring Web module:
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
·   Spring MVC framework:
Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable and accommodates multiple view technologies like JSP, Velocity, and Tiles. But other frameworks can be easily used instead of Spring MVC Framework.

What are features of Spring


What are features of Spring
·   Lightweight:
spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
·   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 comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable and accommodates multiple view technologies like JSP, Velocity, and Tiles. But other frameworks can be easily used instead of Spring MVC Framework.
·   Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to maintain transactions without dealing with low-level issues.
·   JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate: Spring provides best Integration services with Hibernate.

What are the advantages of Spring framework


What are the advantages of Spring framework
The advantages of Spring are as follows:
·   Spring has layered architecture. Use what you need and leave you don't need now.
·   Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
·   Dependency Injection and Inversion of Control Simplifies JDBC
·   Open source and no vendor lock-in.

Sunday, February 27, 2011

What is Spring


What is Spring
Spring is an open source framework created to address 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 while also providing a cohesive framework for J2EE application development.

What is IOC (or Dependency Injection)


What is IOC (or Dependency Injection) ?
The basic concept of the Inversion of Control partner (also known as dependency injection) 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.

Saturday, February 26, 2011

What are the benefits of IOC (Dependency 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 create your objects but describe how they should be created. 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(i.e a class with only one object) or JNDI(.i.e java naming directory interface) 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.
·   IOC supports Loose coupling
·   IOC containers support lazy loading of services



Lazy loading:
when a Java program is compiled it does not know that whether the pointer of a Parent class is either pointing to a parent object or child object, hence it will not bind the methods with pointers at the time of compiling it will wait for runtime to attach methods with pointers this is also called dynamic method dispatch this 'attaching' happens on every method call during runtime
 2nd type of lazy loading is:  remote method invocation
  3rd type:  Anonymous inner class
  4th type: use of 'Class' class

What are the different types of IOC (dependency injection)


What are the different types of IOC (dependency injection)

There are three types of dependency injection:

·   Constructor Injection (e.g. Pico container, Spring etc): This will injects the dependency via a constructor.
In the class OutputHelper               IOutputGenerator outputGenerator; 
                        OutputHelper(IOutputGenerator outputGenerator){
                                     this.outputGenerator = outputGenerator;       }
In the xml file <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
                                     <constructor-arg>
                                                 <bean class="com.mkyong.output.impl.CsvOutputGenerator" />
                                     </constructor-arg>
                        </bean>
·   Setter Injection (e.g. Spring): This is the most popular it will injects the dependency via a setter method.
In the class OutputHelper               IOutputGenerator outputGenerator; 
                        public void setOutputGenerator(IOutputGenerator outputGenerator){
                                    this.outputGenerator = outputGenerator;       }
In the xml file  <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
                                    <property name="outputGenerator" ref="CsvOutputGenerator" />
                                    </property>
                        </bean>
·   Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection