Spring



BeanFactory vs ApplicationContext:-
ApplicationContext already having the power of BeanFactory container plus additional
Resource res = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(res);

ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
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 <bean/> definitions which you have already seen in previous chapters.
The bean definition contains the information called configuration metadata which is needed for the container to know the followings:
  • How to create a bean
  • Bean's lifecycle details
  • Bean's dependencies
All the above configuration metadata translates into a set of the following properties that make up each bean definition.
PropertiesDescription
classThis attribute is mandatory and specify the bean class to be used to create the bean.
nameThis attribute specifies the bean identifier uniquely. In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s).
scopeThis attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter.
constructor-argThis is used to inject the dependencies and will be discussed in next chapters.
propertiesThis is used to inject the dependencies and will be discussed in next chapters.
autowiring modeThis is used to inject the dependencies and will be discussed in next chapters.
lazy-initialization modeA lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
initialization methodA callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter.
destruction methodA callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter.
Spring Configuration Metadata
Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. There are following three important methods to provide configuration metadata to the Spring Container:
  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration
let see sample of XML based configuration file with different bean definitions including lazy initialization, initialization method and destruction method:
<?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">

   <!-- A simple bean definition -->
   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with lazy init set on -->
   <bean id="..." class="..." lazy-init="true">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with initialization method -->
   <bean id="..." class="..." init-method="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with destruction method -->
   <bean id="..." class="..." destroy-method="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions go here -->

</beans>
------------------------------------------------------------------------------------

Bean Scope:-When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, To force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.

The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.
ScopeDescription
singletonThis scopes the bean definition to a single instance per Spring IoC container (default).
prototypeThis scopes a single bean definition to have any number of object instances.
requestThis scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
sessionThis scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-sessionThis scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
This chapter will discuss about first two scopes and remaining three will be discussed when we will discuss about web-aware Spring ApplicationContext.

The singleton scope:

If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.
The default scope is always singleton however, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown below:
<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
    <!-- collaborators and configuration for this bean go here -->
</bean>

The prototype scope:

If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.
To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown below:

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="prototype">
    <!-- collaborators and configuration for this bean go here -->
</bean>
------------------------------------------------------------------------------------------------------------

BeanLifeCycle:--
The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.
Though, there is lists of the activities that take place behind the scenes between the time of bean Instantiation and its destruction, but this chapter will discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction.

To define setup and teardown for a bean, we simply declare the <bean> with init-method and/ordestroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.

Initialization callbacks:

The org.springframework.beans.factory.InitializingBean interface specifies a single method:
void afterPropertiesSet() throws Exception;
So you can simply implement above interface and initialization work can be done inside afterPropertiesSet() method as follows:
public class ExampleBean implements InitializingBean {
   public void afterPropertiesSet() {
      // do some initialization work
   }
}
In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example:
<bean id="exampleBean" 
         class="examples.ExampleBean" init-method="init"/>
Following is the class definition:
public class ExampleBean {
   public void init() {
      // do some initialization work
   }
}

Destruction callbacks

The org.springframework.beans.factory.DisposableBean interface specifies a single method:
void destroy() throws Exception;
So you can simply implement above interface and finalization work can be done inside destroy() method as follows:
public class ExampleBean implements DisposableBean {
   public void destroy() {
      // do some destruction work
   }
}
In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example:
<bean id="exampleBean" 
         class="examples.ExampleBean" destroy-method="destroy"/>
Following is the class definition:
public class ExampleBean {
   public void destroy() {
      // do some destruction work
   }
}
If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment; you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.
It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method.
---------------------------------------------------------------------------------------------------------------
Following is the configuration file Beans.xml required for init and destroy methods:
<?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">

   <bean id="helloWorld" 
       class="com.tutorialspoint.HelloWorld"
       init-method="init" destroy-method="destroy">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>
---------------------------------------------------------------------------------------------------

Default initialization and destroy methods:

If you have too many beans having initialization and or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead framework provides the flexibility to configure such situation using default-init-method and default-destroy-methodattributes on the <beans> element as follows:
<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"
    default-init-method="init" 
    default-destroy-method="destroy">

   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

</beans>
-----------------------------------------------------------------------

Spring Bean Post Processors


BeanPostProcessor gives you a way to do some operations before creating the spring bean 
and immediately after creating the spring bean. This allows you to add some custom logic
before and after spring bean creation. The BeanPostProcessors operate on bean (or object)
instances which means that the Spring IoC container instantiates a bean instance and then 
BeanPostProcessor interfaces do their work.

Notice- that the init and destroy methods related to bean are different from bean post processors.
 BeanPostProcessors are common for all beans. This example clearly shows the difference 
 from them.
An ApplicationContext automatically detects any beans that are defined with implementation of theBeanPostProcessor interface and registers these beans as post-processors, to be then called appropriately by the container upon bean creation.

see example
http://www.tutorialspoint.com/spring/spring_bean_post_processors.htm
----------------------------------------------------------------------------------------------

What is the difference between BeanPostProcessor and init/destroy method in Spring?

you can check here

Apart from that it's also important to understand that both beanPostProcessor and init and destroy methods are part of the Spring bean life cycle.
BeanPostProcessor class has two methods.
1) postProcessBeforeInitialization - as name clearly says that it's used to make sure required actions are taken before initialization. e.g. you want to load certain property file/read data from the remote source/service.
2) postProcessAfterInitialization - any thing that you want to do after initialization before bean reference is given to application.
Sequence of the questioned methods in life cycle as follows :
1) BeanPostProcessor.postProcessBeforeInitialization()
2) init()
3) BeanPostProcessor.postProcessAfterInitialization()
4) destroy()
You may check this by writing simple example having sysout and check their sequence

Constructor injection vs Setter injection:-
Thus, DI exists in two major variants and following two sub-chapters will cover both of them with examples:
S.N.Dependency Injection Type & Description
1Constructor-based dependency injection
Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
2Setter-based dependency injection
Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.
Code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies, and does not know the location or class of the dependencies rather everything is taken care by the Spring Framework.
---------------------------------------------------------------------------------------------------------------------------------------------------
Injecting Java Collectiong:-
?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">

   <!-- Definition for javaCollection -->
   <bean id="javaCollection" class="com.tutorialspoint.JavaCollection">

      <!-- results in a setAddressList(java.util.List) call -->
      <property name="addressList">
        <list>
           <value>INDIA</value>
           <value>Pakistan</value>
           <value>USA</value>
           <value>USA</value>
        </list>
      </property>

     <!-- results in a setAddressSet(java.util.Set) call -->
     <property name="addressSet">
        <set>
           <value>INDIA</value>
           <value>Pakistan</value>
           <value>USA</value>
           <value>USA</value>
        </set>
      </property>

     <!-- results in a setAddressMap(java.util.Map) call -->
     <property name="addressMap">
        <map>
           <entry key="1" value="INDIA"/>
           <entry key="2" value="Pakistan"/>
           <entry key="3" value="USA"/>
           <entry key="4" value="USA"/>
        </map>
      </property>

     <!-- results in a setAddressProp(java.util.Properties) call -->
     <property name="addressProp">
        <props>
           <prop key="one">INDIA</prop>
           <prop key="two">Pakistan</prop>
           <prop key="three">USA</prop>
           <prop key="four">USA</prop>
        </props>
      </property>

   </bean>

</beans>
-----------------------------------------------------------------------------------------

Spring Annotation Based Configuration


Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Annotation injection is performed before XML injection, thus the later configuration will override the former for properties wired through both approaches.
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. So consider to have following configuration file in case you want to use any annotation in your Spring application.
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <!-- bean definitions go here -->

</beans>


------------------------------------------------------------
Making a Spring bean Applicationcontext aware :-
http://blog.imaginea.com/making-a-spring-bean-applicationcontext-aware/
Best of Spring:-
http://www.java4s.com/spring/spring-dependency-injection-with-set-collection-property/

http://docs.spring.io/spring/docs/3.2.1.RELEASE/spring-framework-reference/html/beans.html#beans-factory-scopes

http://www.mkyong.com/
---------------------------------------------------------------------------------------
Why Spring LeighWeight:-

Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

AOP:--
it's concept which is developed by aspectj framework later  spring as well. we need to deep look now :-
http://en.wikipedia.org/wiki/Aspect-oriented_programming

other good explanation:-
http://docs.jboss.org/jbossaop/docs/2.0.0.GA/docs/aspect-framework/userguide/en/html/what.html

stackoverflow definition
http://stackoverflow.com/questions/242177/what-is-aspect-oriented-programming:-

Spring AOP VS AspectJ:--
Both the technique provided by different -2 company having common goal:--
AspectJ:-
Spring Aop:-
pros/cons of both:--
Spring-AOP Pros
  • It is simpler to use than AspectJ, since you don't have to use LTW (load-time weaving) or the AspectJ compiler.
  • This can be change to AspectJ AOP when you use @Aspect annotation based Spring AOP.
  • This use Proxy pattern and Decorator pattern
Spring-AOP Cons
  • This is proxy-based AOP, so basically you can only use method-execution pointcut.
  • Aspects aren't applied when calling another method within the same class.
  • There can be a little runtime overhead.
  • Spring-AOP cannot add an aspect to anything that is not created by the Spring factory
AspectJ Pros
  • This supports all pointcuts. This means you can do anything.
  • There is little runtime overhead.
AspectJ Cons
  • Be careful. Check if your aspects are weaved to only what you wanted to be weaved.
  • You need extra build process with AspectJ Compiler or have to setup LTW (load-time weaving)
Additional point from stackoverflow:-

-An additional note: If performance under high load is important, you'll want AspectJ which is 9-35x faster than Spring AOP. 10ns vs 355ns might not sound like much, but I've seen people using LOTS of Aspects. 10K's worth of aspects. In these cases, your request might hit a thousands of aspects. In that case you're adding ms to that request.

--------------------------------------------------------------------------------------------------------------------



Spring Framework : ApplicationContext instantiation for web applications in Spring Framework

------------------------------------------------------------------------
In web application ApplicationContext is created using Context Loaders. there are two implementations of context loader.
  • ContextLoaderListener : It is listener implementation that is added to web.xml file.
  • ContextLoaderServlet : It is servlet implementation that is configured with load-on-startup tag in web.xml.

 ContextLoaderListener is simple way to use the spring in web application. this listener accept contextConfigLocation parameter from context-parama.
You have to enter following code in web.xml file

define contextConfigLocation parameter in context-param tag.

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/services.xml</param-value>
</context-param>
 
services.xml is the Spring configuration file in which you define beans.

Add the ContextLoaderListener listener.

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

Here is the complete source code for the example demonstrating this.

InputService.java

import java.util.Random;
import java.util.Scanner;
public class InputService {
    public int getIntValue() {
        Random r=new Random();
        int val=r.nextInt();
        System.out.println("Returning value = "+val);
        return val;
    }
}

OutputService.java

public class OutputService{
    public int write(int x) {
        System.out.println("Output is "+x);
        return x;
    }
}


CalServlet .java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CalServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        CalcMachine cal = (CalcMachine) ac.getBean("cal");
        response.getWriter().print("Adding of numbers is = " + cal.doAdd());
        response.getWriter().close();
    }
}

services.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-3.0.xsd">

    <bean id="in" class="InputService"/>
    <bean id="out" class="OutputService"/>
    
    <bean id="cal" class="CalcMachine">
        <property name="inputService">
            <ref bean="in" />
        </property>
        <property name="outputService">
            <ref bean="out" />
        </property>
    </bean>
</beans>

 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DI2_web</display-name>

    <servlet>
        <description></description>
        <display-name>CalServlet</display-name>
        <servlet-name>CalServlet</servlet-name>
        <servlet-class>CalServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CalServlet</servlet-name>
        <url-pattern>/CalServlet</url-pattern>
    </servlet-mapping>

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

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

\
---------------------------------------------------------------------------------------------------------------------------------
SpringWebService:--

http://briansjavablog.blogspot.in/2013/01/spring-web-services-tutorial.html

http://docs.spring.io/spring-ws/site/reference/html/what-is-spring-ws.html

-----------------------------------------------------------------------------------------------------------------------------------------

How to assign more then one xml file to spring. i means multiple xml together to single container.

http://stackoverflow.com/questions/600095/splitting-applicationcontext-to-multiple-files


-----------------------------------------------------------------------------------------------------------------------------------------



No comments:

Post a Comment