Showing posts with label Bean scopes in Spring. Show all posts
Showing posts with label Bean scopes in Spring. Show all posts

Spring Bean Configuration Examples

  • XML file that can be developed either based on DTD rules or Schema rules. The XMLfile of certain software technology based applications either based on DTD or Schema rules supplied by that technology.
  • Contains Spring Bean configuration to make Spring Containers to recognize Spring.
  • Contains configuration for setter injections and constructor injections.
  • Any filename.xml can be taken as Spring Bean configuration file name and also contains     some misecllanious configurations related to Spring Beans.

Setting the Bean Properties :

public class ExampleBean {

      private String s;
      private int i;

      public void setStringProperty (String s) { this.s = s; }
      public void setIntegerProperty (int i) { this.i = i; }
  }



  <bean id="exampleBean" class="ExampleBean">
       <property name="stringProperty"><value>Hi!</value></property>
       <property name="integerProperty"><value>1</value></property>
  </bean>


Example:
<property name="intProperty"><value>7</value></property>

<property name="doubleProperty"><value>0.25</value></property>

<property name="booleanProperty"><value>true</value></property>
 

<property name="colorProperty"><value>0,255,0</value></property>

java.awt.Color is initialized with RGB values.

Bean Constructor Configuration:

public class ExampleBean {
      private AnotherBean beanOne;
      private YetAnotherBean beanTwo;
      private int i;
      public ExampleBean (AnotherBean b1, YetAnotherBean b2, int i) {
          this.beanOne = b1;
          this.beanTwo = b2;
          this.i = i;
      }
  }

  <bean id="exampleBean" class="ExampleBean">
      <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
      <constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
      <constructor-arg><value>1</value></constructor-arg>
  </bean>

  <bean id="anotherExampleBean" class="AnotherBean"/>
  <bean id="yetAnotherBean" class="YetAnotherBean"/>



Using Java.util.Properties Example:

<property name="propertiesProperty">
       <value>
           foo=1
           bar=2
           baz=3
       </value>
  </property>

  <property name="propertiesProperty">
       <props>
           <prop key="foo">1</prop>
           <prop key="bar">2</prop>
           <prop key="baz">3</prop>
       </props>
  </property>


List Example:

<property name="listProperty">
      <list>
           <value>a list element</value>
           <ref bean="otherBean"/>
           <ref bean="anotherBean"/>
      </list>
  </property>


Set Example:
 
  <property name="setProperty">
      <set>
           <value>a set element</value>
           <ref bean="otherBean"/>
           <ref bean="anotherBean"/>
      </set>
  </property> 


Map Example:

<property name="mapProperty">
       <map>
           <entry key="JavaStuff">
                <value>Spring Example</value>
           </entry>
           <entry key="yup a ref">
                <ref bean="otherBean"/>
           </entry>
       </map>
  </property> 


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Purpose of the ApplicationContext in Spring

While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds ApplicationContext, which enhances BeanFactory functionality in a more framework-oriented style. 

A bean factory is fine for simple applications, but to take advantage of the full power of the Spring Framework, you’ll probably want to load your application beans using Spring’s more advanced container, the application context.

Many users will use ApplicationContext in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as ContextLoader to automatically start an ApplicationContext as part of the normal startup process of a J2EE web-app. Of course, it is still possible to programmatically create an ApplicationContext.

The basis for the context package is the ApplicationContext interface, located in the org.springframework.context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. 



You could also implement your own ApplicationContext and add support for loading from other resources (such as a database). While many Contexts are available for loading beans, you’ll only need a few, which are listed below. The others are internal classes that are used by the framework itself.

1 )  ClassPathXmlApplicationContext: Loads context files from the classpath (that is, WEB-INF/classes or WEB-INF/lib for JARs) in a web application. Initializes using a 

                      new ClassPathXmlApplicationContext(path)
where path is the path to the file.


2 ) FileSystemXmlApplicationContext: Loads context files from the file system, which is nice for testing. Initializes using a
            new FileSystemXmlApplicationContext (path)
where path is a relative or absolute path to the file. The path argument can also be a String array of paths.

3. XmlWebApplicationContext: Loads context files internally by the ContextLoaderListener, but can be used outside of it. For instance, if you are running a container that doesn’t load Listeners in the order specified in web.xml, you may have to use this in another Listener. Below is the code to use this Loader.

XmlWebApplicationContext context = 
            new XmlWebApplicationContext();
context.setServletContext(ctx);
context.refresh();

Once you’ve obtained a reference to a context, you can get references to beans using  

   ctx.getBean(“beanId”)
You will need to cast it to a specific type, but that’s the easy part. Of the above contexts, ClassPathXmlApplicationContext is the most flexible. It doesn’t care where the files are, as long as they’re in the classpath. This allows you to move files around and simply change the classpath.



Related Topics :

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Spring IoC Constructor Injection Example - Tutorial

Constructor Injection: In constructor injection IoC container users construction of dependent class to set the instance of dependency class. We will see example of constructor injection in upcoming tutorials using Spring IoC framework.



SpringExample.java

package com.javastuff.spring;

 public class SpringExample {
 public String message;

 /**
  * @return the message
  */
 public String getMessage() {
  return message;
 }

 /**
  * @param message
  *            the message to set
  */
 public void setMessage(String message) {
  this.message = message;
 }

 public SpringExample(String mess) {
  this.message = mess;
 }
 }


ApplicationContext.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" 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">

 <bean id="springExample" class="com.javastuff.spring.SpringExample">
  <constructor-arg index="0" type="java.lang.String"
   value="Hello Friend!!!!" />
 </bean>

</beans>
TestClass.java
package com.javastuff.Test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javastuff.spring.SpringExample;

public class TestClass {
 public static void main(String[] args) {
  BeanFactory factory = new ClassPathXmlApplicationContext(
    "ApplicationContext.xml");
  SpringExample se = (SpringExample) factory.getBean("springExample");
  System.out.println(" Message  : " + se.getMessage());
 }
}


Output :
 Message  : Hello Friend!!!!



Related Topics :



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Spring Basic Bean Creation Example -Tutorial

Bean Creation :
  • Direct instantiation
    • <bean id=“beanId” class=“className”>
  • BeanFactory instantiation
    • Same syntax but class is subclass of BeanFactory
    • getObject() called to obtain Bean
  • Static Factory
    • <bean id=“beanId” class=“className" factory-method=" staticCreationMethod“>
  • Instance Factory Method
    • <bean id=“beanId” factory-bean=“existingBeanId" factory-method=“nonStaticCreationMethod">
  • Beans may be singletons or “prototypes”
    • Attribute singleton=“false” causes instantiation with each getBean() lookup
    • Singleton is default
  • XmlBeanFactory pre-instantiates singletons
    • May be overridden on per-instance basis by lazy-init=“true”
  • Beans may also be marked abstract, allowing reuse of attribute values through inheritance

Basic Bean Creation :

Lets start with a simple program about IoC. 
Spring IoC Bean class :


package com.javastuff.spring;

public class SpringExample {
 public String message = " Welcome to Javastuff ";

 /**
  * @return the message
  */
 public String getMessage() {
  return message;
 }

 /**
  * @param message
  *            the message to set
  */
 public void setMessage(String message) {
  this.message = message;
 }
}

 
Spring IoC Container configuration file :
ApplicationContext.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" 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">
 
 <bean id="springExample" class="com.javastuff.spring.SpringExample" />

</beans>

Test Class :
package com.javastuff.Test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javastuff.spring.SpringExample;

public class TestClass {
 public static void main(String[] args) {
  BeanFactory factory = new ClassPathXmlApplicationContext(
    "ApplicationContext.xml");
  SpringExample se = (SpringExample) factory.getBean("springExample");
  System.out.println(" Message  : " + se.getMessage());
 }
}


Output :
Message  :  Welcome to Javastuff 


    Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

    Make sure to activate your subscription by clicking on the activation link sent to your email

    Bean Creation in spring - Tutorial Part - 3

    Bean Creation :
    • Direct instantiation
      • <bean id=“beanId” class=“className”>
    • BeanFactory instantiation
      • Same syntax but class is subclass of BeanFactory
      • getObject() called to obtain Bean
    • Static Factory
      • <bean id=“beanId” class=“className" factory-method=" staticCreationMethod“>
    • Instance Factory Method
      • <bean id=“beanId” factory-bean=“existingBeanId" factory-method=“nonStaticCreationMethod">
    • Beans may be singletons or “prototypes”
      • Attribute singleton=“false” causes instantiation with each getBean() lookup
      • Singleton is default
    • XmlBeanFactory pre-instantiates singletons
      • May be overridden on per-instance basis by lazy-init=“true”
    • Beans may also be marked abstract, allowing reuse of attribute values through inheritance
    Autowiring Properties :
    • Beans may be auto-wired (rather than using <ref>)
      • Per-bean attribute autowire
      • Explicit settings override
    • autowire=“name”
      • Bean identifier matches property name
    • autowire=“type”
      • Type matches other defined bean
    • autowire=”constructor”
      • Match constructor argument types
    • autowire=”autodetect”
      • Attempt by constructor, otherwise “type”
    ApplicationContext :
    • Extends functionality of BeanFactory
    • Pre-instantiates singleton beans
    • Detects and registers BeanPostProcessors and BeanFactoryPostProcessors
    • Supports nesting of contexts
    • ApplicationListener and ApplicationEvents
      • Initialized and closed predefined
      • Custom may be created
    • MessageSource provides i18n messaging
      • <bean id=”messageSource” class=”...ResourceBundleMessageSource”/> Contains list of bundle base names.

    Spring Framework Tutorial - Part1

    What is Spring ?
    • Spring is a Framework, it Provides an infrastructure of classes that make it easier to accomplish tasks.
    • Spring is a Container,it Creates objects and makes them available to your application.
    • A lightweight framework that addresses each tier in a Web application.                     
      1. Presentation layer  :  An MVC framework that is most similar to Struts but is more powerful and easy to use.                                              
      2. Business layer  :  Lightweight IoC container and AOP support (including built in aspects).                                                                      
      3. Persistence layer :  DAO template support for popular ORMs and JDBC
    • Promotes decoupling and reusability.  
    • POJO Based.
    • Removes common code issues like leaking connections and more.
    • Built in aspects such as transaction management.  
     What does Spring provide ?
    • Lightweight container and framework
      • Most of your code will be unaware of the Spring framework
      • Use only the parts you of Spring you want
    • Manages dependencies between your objects
      • Encourages use of interfaces.
      • Lessens “coupling” between objects.
    • Cleaner separation of responsibilities.
      • Put logic that applies to many objects in one single place.
      • Separate the class’s core responsibility from other duties.
    • Simplifies database integration
      • Spring JDBC
      • Hibernate
      • iBATIS
      • Java Persistence API
    Simplify your code with Spring :
    • Enables you to stop polluting code
    • No more custom singleton objects
      • Beans are defined in a centralized configuration file
    • No more custom factory object to build and/or locate other objects
    • DAO simplification
      • Consistent CRUD
      • Data access templates
      • No more copy-paste try/catch/finally blocks
      • No more passing Connection objects between methods
      • No more leaked connections
    • POJO Based
    • Refactoring experience with Spring
    • Caution Spring is addictive.
    IoC(Inversion of Control) container :
    • Setter based and constructor based dependency injection
    • Portable across application servers
    • Promotes good use of OO practices such as programming to interfaces.
    • Beans managed by an IoC container are reusable and decoupled from business logic
    AOP (Aspect-Oriented Programming): 
    • Spring uses Dynamic AOP Proxy objects to provide cross-cutting services
    • Reusable components
    • Aopalliance support today
    • Integrates with the IoC container
    • AspectJ support in Spring 1.1

    Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

    Make sure to activate your subscription by clicking on the activation link sent to your email

    Bean scopes in Spring


    Bean scopes

    When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.
    You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-awareApplicationContext).
    The scopes supported out of the box are listed below:

    Bean scopes
    ScopeDescription
    singleton
    Scopes a single bean definition to a single object
    instance per Spring IoC container.
    prototype
    Scopes a single bean definition to any number
    of object instances.
    request
    Scopes a single bean definition to the lifecycle
    of a single HTTP request; that is each and every
    HTTP request will have its own instance of a bean 
    created off the back of a single bean definition.
    Only valid in the context of a web-aware Spring
     ApplicationContext.
    session
    Scopes a single bean definition to the lifecycle of a HTTP Session.
    Only valid in the context of a web-aware
    SpringApplicationContext.
    global session
    Scopes a single bean definition to the lifecycle of a g
    lobal HTTP Session. Typically only valid when used
    in a portlet context. Only valid in the context of a web-aware
    Spring ApplicationContext.

    The singleton scope

    When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
    To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will createexactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.
    Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hard codes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you would write configuration like so:
    <bean id="accountService" class="com.foo.DefaultAccountService"/>
    
    <!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
    <bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>
    
    <!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
    <bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>

    The prototype scope

    The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
    The following diagram illustrates the Spring prototype scope. Please note that a DAO would not typically be configured as a prototype, since a typical DAO would not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.
    To define a bean as a prototype in XML, you would write configuration like so:
    <!-- using spring-beans-2.0.dtd -->
    <bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
    
    <!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
    <bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>
    There is one quite important thing to be aware of when deploying a bean in the prototype scope, in that the lifecycle of the bean changes slightly. Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto. (One possible way to get the Spring container to release resources used by prototype-scoped beans is through the use of a custom bean post-processor which would hold a reference to the beans that need to be cleaned up.)
    In some respects, you can think of the Spring containers role when talking about a prototype-scoped bean as somewhat of a replacement for the Java 'new' operator. All lifecycle aspects past that point have to be handled by the client. (The lifecycle of a bean in the Spring container is further described in the section entitled  “Lifecycle callbacks

     Singleton beans with prototype-bean dependencies

    When using singleton-scoped beans that have dependencies on beans that are scoped as prototypes, please be aware thatdependencies are resolved at instantiation time. This means that if you dependency inject a prototype-scoped bean into a singleton-scoped bean, a brand new prototype bean will be instantiated and then dependency injected into the singleton bean... but that is all. That exact same prototype instance will be the sole instance that is ever supplied to the singleton-scoped bean, which is fine if that is what you want.
    However, sometimes what you actually want is for the singleton-scoped bean to be able to acquire a brand new instance of the prototype-scoped bean again and again and again at runtime. In that case it is no use just dependency injecting a prototype-scoped bean into your singleton bean, because as explained above, that only happens once when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you are in the scenario where you need to get a brand new instance of a (prototype) bean again and again and again at runtime,
    If you are referencing the 'spring-beans.dtd' DTD in a bean definition file(s), and you are being explicit about the lifecycle scope of your beans you must use the "singleton" attribute to express the lifecycle scope (remembering that the singleton lifecycle scope is the default). If you are referencing the 'spring-beans-2.0.dtd' DTD or the Spring 2.0 XSD schema, then you will need to use the "scope" attribute (because the "singleton" attribute was removed from the definition of the new DTD and XSD files in favor of the "scope" attribute).
    To be totally clear about this, this means that if you use the "singleton" attribute in an XML bean definition then you must be referencing the 'spring-beans.dtd' DTD in that file. If you are using the "scope" attribute then you must be referencing either the 'spring-beans-2.0.dtd' DTD or the 'spring-beans-2.5.xsd' XSD in that file.

    The other scopes

    The other scopes, namely requestsession, and global session are for use only in web-based applications (and can be used irrespective of which particular web application framework you are using, if indeed any). In the interest of keeping related concepts together in one place in the reference documentation, these scopes are described here.

    The scopes that are described in the following paragraphs are only available if you are using a web-aware SpringApplicationContext implementation (such as XmlWebApplicationContext). If you try using these next scopes with regular Spring IoC containers such as the XmlBeanFactory orClassPathXmlApplicationContext, you will get an IllegalStateException complaining about an unknown bean scope.

    Initial web configuration

    In order to support the scoping of beans at the requestsession, and global session levels (web-scoped beans), some minor initial configuration is required before you can set about defining your bean definitions. Please note that this extra setup is notrequired if you just want to use the 'standard' scopes (namely singleton and prototype).
    Now as things stand, there are a couple of ways to effect this initial setup depending on your particular Servlet environment...
    If you are accessing scoped beans within Spring Web MVC, i.e. within a request that is processed by the SpringDispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet andDispatcherPortlet already expose all relevant state.
    When using a Servlet 2.4+ web container, with requests processed outside of Spring's DispatcherServlet (e.g. when using JSF or Struts), you need to add the following javax.servlet.ServletRequestListener to the declarations in your web application's 'web.xml' file.
    <web-app>
      ...
      <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
      </listener>
      ...
    </web-app>
    If you are using an older web container (Servlet 2.3), you will need to use the provided javax.servlet.Filter implementation. Find below a snippet of XML configuration that has to be included in the 'web.xml' file of your web application if you want to have access to web-scoped beans in requests outside of Spring's DispatcherServlet on a Servlet 2.3 container. (The filter mapping depends on the surrounding web application configuration and so you will have to change it as appropriate.)
    <web-app>
      ..
      <filter> 
        <filter-name>requestContextFilter</filter-name> 
        <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
      </filter> 
      <filter-mapping> 
        <filter-name>requestContextFilter</filter-name> 
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      ...
    </web-app>
    That's it. DispatcherServletRequestContextListener and RequestContextFilter all do exactly the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain.

    The request scope

    Consider the following bean definition:
    <bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
    With the above bean definition in place, the Spring container will create a brand new instance of the LoginAction bean using the'loginAction' bean definition for each and every HTTP request. That is, the 'loginAction' bean will be effectively scoped at the HTTP request level. You can change or dirty the internal state of the instance that is created as much as you want, safe in the knowledge that other requests that are also using instances created off the back of the same 'loginAction' bean definition will not be seeing these changes in state since they are particular to an individual request. When the request is finished processing, the bean that is scoped to the request will be discarded.

    The session scope

    Consider the following bean definition:
    <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
    With the above bean definition in place, the Spring container will create a brand new instance of the UserPreferences bean using the 'userPreferences' bean definition for the lifetime of a single HTTP Session. In other words, the 'userPreferences'bean will be effectively scoped at the HTTP Session level. Just like request-scoped beans, you can change the internal state of the instance that is created as much as you want, safe in the knowledge that other HTTP Session instances that are also using instances created off the back of the same 'userPreferences' bean definition will not be seeing these changes in state since they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session will also be discarded.

    The global session scope

    Consider the following bean definition:
    <bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession"/>
    The global session scope is similar to the standard HTTP Session scope (described immediately above), and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global sessionscope are scoped (or bound) to the lifetime of the global portlet Session.
    Please note that if you are writing a standard Servlet-based web application and you define one or more beans as having global session scope, the standard HTTP Session scope will be used, and no error will be raised.


    Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

    Make sure to activate your subscription by clicking on the activation link sent to your email