Showing posts with label Core Spring. Show all posts
Showing posts with label Core Spring. Show all posts

Wednesday, 17 July 2013

Basic Spring Example With ClassPathXmlApplicationContext & AnnotationConfigApplicationContext

0 comments
Spring Framework Jars -


Project Structure -





User.java
package com.beans;

public class User {

 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

Order.java
package com.beans;

public class Order {

 private String orderName;
 private Integer price;
 public String getOrderName() {
  return orderName;
 }
 public void setOrderName(String orderName) {
  this.orderName = orderName;
 }
 public Integer getPrice() {
  return price;
 }
 public void setPrice(Integer price) {
  this.price = price;
 }
 
 
}

JavaConfigBean.java
package com.beans;

public class JavaConfigBean {

 private String version;

 public String getVersion() {
  return "Harit";
 }

 public void setVersion(String version) {
  this.version = version;
 }
 
}

Configure java beans using xml configuration file SpringBeans.xml

 
 
  
 
    
    

Order.xml

 
 
  
  
 
 

Java Class based bean configuration AppConfig.java
package com.javaconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.beans.JavaConfigBean;

@Configuration
public class AppConfig {

 @Bean(name="javaconfigbean")
 public JavaConfigBean getJavaConfigBean()
 {
  return new JavaConfigBean();
 }
}

Test the app Test.java
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.beans.JavaConfigBean;
import com.beans.Order;
import com.beans.User;
import com.javaconfig.AppConfig;

public class Test {

 public static void main(String[] args) {
  
  //For Class Path Xml Application Context
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringBeans.xml");  
  User user = (User) applicationContext.getBean("userbean");
  System.out.println(user.getName());
  
  
  //Import Order.xml's Bean
  Order order = (Order) applicationContext.getBean("orderbean");
  System.out.println(order.getOrderName());
  
  
  //For Annotation Based ApplicationContext
  ApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(AppConfig.class);
  JavaConfigBean javaConfigBean = (JavaConfigBean) applicationContext2.getBean("javaconfigbean");
  System.out.println(javaConfigBean.getVersion());
 }
}

Output:
Harit Kumar
Bread
Harit

Wednesday, 5 June 2013

Spring 3 - Task Scheduling

0 comments
In this tutorial we will explore Spring 3's task scheduling support using annotations. We will be using @Scheduled and @Async annotations. Spring also provides scheduling support using the Quartz Scheduler, and via XML configuration . We will build our application on top of a simple Spring MVC 3 application. Although MVC is not required, I would like to show how easy it is to integrate.

@Scheduled Annotation
@Scheduled annotation  add to a method along with trigger metadata.

To enable this annotation we need to add the annotation-driven element:

You also need to add the component-scan element. We didn't enable it here since it's already added in the applicationContext.xml .

 
 
 
 
 
 
 
 
  
 
 
 
 



spring-scheduler

 
 

 
 
 
 
 
 
  
 
  
                
                

Worker

SyncWorker

This worker is synchronous which means if we have to call this worker 10 times, it will block the other workers. They cannot start immediately until the first one is finished. We didn't do anything to make this implementation synchronous. It's the default.

The class that calls this SyncWorker is a scheduler service.
Notice the @Scheduled annotation in the doSchedule() method. This tells Spring to mark this method for task scheduling. Inside the @Scheduled, there's a metadata that describes when the method should be triggered. The following metadata all have the same value (5 seconds) but they are interpreted differently:

fixedDelay=5000
fixedRate=5000
cron="*/5 * * * * ?"

fixedDelay: An interval-based trigger where the interval is measured from the completion time of the previous task. fixedRate: An interval-based trigger where the interval is measured from the start time of the previous task. cron: A cron-based trigger Running the application gives us the following logs:
Notice how the tasks are run sequentially every 5 seconds.

What if we want to run the workers asynchronously, meaning we don't want to wait for worker 1 to finish before we start worker 2, or worker 3, and so forth? There are valid reasons like efficient use of physical resources and time.

To make a worker asychronous, we add the @Async annotation in the method that needs to be asychronous.

The @Async Annotation

    The @Async annotation can be provided on a method so that invocation of that method will occur asynchronously. In other words, the caller will return immediately upon invocation and the actual execution of the method will occur in a task that has been submitted to a Spring TaskExecutor.

    Source: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

To enable this annotation we use the same annotation-driven element.

Let's examine an actual example. We'll create a new class AsyncWorker that implements the Worker interface earlier.

AsyncWorker

This worker is asychronous. The caller (the scheduler service) will return immediately upon invocation.

The class that calls this AsyncWorker is the same scheduler service we had earlier. We
just need to change the value of @Qualifier Use Of @Scheduled Annotation
//@Scheduled(fixedDelay=5000)
 //@Scheduled(fixedRate=5000)
 @Scheduled(cron="*/5 * * * * ?")
 public void doSchedule() {
  logger.debug("Start schedule");
  
  for (int i = 0; i < 5; i++) {
   logger.debug("Delegate to worker " + i);
   worker.work();
        }
  
  logger.debug("End schedule");
 }

Wednesday, 1 May 2013

Schedule tasks in Spring 3 Using @Scheduled

0 comments

Explaining @Scheduled annotation

This annotation is used for task scheduling. The trigger information needs to be provided along with this annotation. You can use the properties fixedDelay/fixedRate/cron to provide the triggering information.
  1. fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.
  2. fixedDelay specifically controls the next execution time when the last execution finishes.
  3. cron is a feature originating from Unix cron utility and has various options based on your requirements.
Example usage can be as below:

@Scheduled(fixedDelay =30000)
public void demoServiceMethod () {... }

@Scheduled(fixedRate=30000)
public void demoServiceMethod () {... }

@Scheduled(cron="0 0 * * * *")
public void demoServiceMethod () {... }

To use @Scheduled in your spring application, you must first define below xml namespace and schema location definition in your application-config.xml file.
 
xmlns:task="http://www.springframework.org/schema/task"

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-3.0.xsd

Above additions are necessary because we will be using annotation based configurations. Now add below definition to enable annotations.

 



Next step is to create a class and a method inside the class like below:
public class DemoService
{
 @Scheduled(cron="*/5 * * * * ?")
 public void demoServiceMethod()
 {
  System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());
 }
}
Using @Scheduled annotation would in turn make Spring container understand that the method underneath this annotation would run as a job. Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not return any values too. If you want the external objects to be used within your @Scheduled methods, you should inject them into the DemoService class using autowiring rather than passing them as parameters to the @Scheduled methods.

And application configuration will look like this:
 
< ?xml  version="1.0" encoding="UTF-8"?>


    
    

Monday, 8 April 2013

Call Stored Procedures in Spring

6 comments
There are multiple ways to call stored procedure in Spring Framework
1. query() method from JdbcTemplate to call stored procedures
2. extend abstract class StoredProcedure to call stored procedures

Step 1: Create a store Procedure

mysql> DELIMITER // 
mysql> create procedure usp_GetEmployeeName(IN id INT, OUT name VARCHAR(20)) 
-> begin 
-> select emp_name into name from employee where emp_id = id; 
-> end//

 Query OK, 0 rows affected (0.52 sec) 
 
 
 mysql> DELIMITER ;


Step2: Java Class which wraps Stored procedure
 In this example, we have extended abstract class StoredProcedure in our class called, EmployeeSP. This is declared as nested class inside EmployeeDAO because its only used by this class, if your stored procedure is used my multiple DAO classes, than you can also make it a top level class. If you look at constructor of EmployeeSP, it calls super class constructor and passes datasource and name of database stored procedure. We have also declared two stored procedure parameters, one is IN parameter id, and other is OUT parameter. Input to stored procedure is passed using IN parameter, and output from stored procedure is read using OUT parameter. Your stored procedure can have multiple IN and OUT parameter. StoredProcedure class also provide several execute() methods, which can be invoked to call stored procedure and get result. It return result as Map, where key is OUT parameter, and value is result of stored procedure.

import java.sql.Types; 
import java.util.Map; 
import javax.sql.DataSource; 
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter; 
import org.springframework.jdbc.core.SqlParameter; 
import org.springframework.jdbc.object.StoredProcedure;
public class EmployeeDao 
{ 
 private JdbcTemplate jdbcTemplate;
 private EmployeeSP sproc; 
 public void setDataSource(DataSource source)
 { 
  this.jdbcTemplate = new JdbcTemplate(source); 
  this.sproc = new EmployeeSP(jdbcTemplate.getDataSource()); 
  } 
 
 /* * wraps stored procedure call */ 
 public String getEmployeeName(int emp_id)
 { 
  return (String) sproc.execute(emp_id); 
 } 
 
 /* * Inner class to implement stored procedure in spring. */ 
 private class EmployeeSP extends StoredProcedure
 { 
  private static final String SPROC_NAME = "usp_GetEmployeeName"; 
  public EmployeeSP( DataSource datasource )
  { 
   super( datasource, SPROC_NAME ); 
   declareParameter( new SqlParameter( "id", Types.INTEGER) ); //declaring sql in parameter to pass input 
   declareParameter( new SqlOutParameter( "name", Types.VARCHAR ) ); //declaring sql out parameter 
   compile(); 
  } 
  
  public Object execute(int emp_id)
  { 
   Map results = super.execute(emp_id); 
   return results.get("name"); //reading output of stored procedure using out parameters 
   } 
  } 
 }
   }
  }
}


Step3: Test stored procedure

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
/* * Main class to start and test this Java application */ 
public class Main 
{ 
 public static void main(String args[])
 { 
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml"); 
  EmployeeDao dao = (EmployeeDao) ctx.getBean("employeeDao"); //calling stored procedure using DAO method 
  System.out.println("Employee name for id 103 is : " + dao.getEmployeeName(103)); } } 
 }
}


Output:
2013-01-17 23:56:34,408 0 [main] DEBUG EmployeeDao$EmployeeSP - Compiled stored procedure. Call string is [{call usp_GetEmployeeName(?, ?)}] 
2013-01-17 23:56:34,439 31 [main] DEBUG EmployeeDao$EmployeeSP - RdbmsOperation with SQL [usp_GetEmployeeName] compiled 
Employee name for id 103 is : Jack


spring-config.xml


        
                
                        
                                classpath:jdbc.properties
                        
                
        

    
        
        
        
        
    
      
        
                
        


Monday, 1 April 2013

Autowire a Bean Spring

0 comments
SpringBeans.xml


 
 
 
  
  
 
  
 
  
 
 
Customer.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class Customer {

 @Autowired
 private Person person;
 private int type;
 private String action;

 public Person getPerson() {
  return person;
 }

 public void setPerson(Person person) {
  this.person = person;
 }

 public int getType() {
  return type;
 }

 public void setType(int type) {
  this.type = type;
 }

 public String getAction() {
  return action;
 }

 public void setAction(String action) {
  this.action = action;
 }

 @Override
 public String toString() {
  return "Customer [person=" + person + ", type=" + type + ", action="
    + action + "]";
 }

 
}
Person.java
package com;

public class Person {
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return "Person [name=" + name + "]";
 }

 
}
App.java
package com;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");

  Customer cust = (Customer) context.getBean("customer");
  Person per = (Person) context.getBean("person");
  
  System.out.println(cust);
  System.out.println(per);
 }
}
Output: 
Customer [person=Person [name=harit], type=1, action=buy]
Person [name=harit]

Auto-Wiring Beans Spring

0 comments

In Spring, 5 Auto-wiring modes are supported

no – Default, no auto wiring, set it manually via “ref” attribute
byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.
byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.
constructor – byType mode in constructor argument.
autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.
Customer and Person Bean Classes
public class Customer 
{
 private Person person;
 
 public Customer(Person person) {
  this.person = person;
 }
 
 public void setPerson(Person person) {
  this.person = person;
 }
 //...
}
public class Person 
{
 //...
}
1. Auto-Wiring ‘no’ 
This is the default mode, you need to wire your bean via ‘ref’ attribute.

                  
 
 
 
2. Auto-Wiring ‘byName’ 
Auto-wire a bean by property name. In this case, since the name of “person” bean is same with the name of the “customer” bean’s property (“person”), so, Spring will auto wired it via setter method – “setPerson(Person person)“.

 
 
3. Auto-Wiring ‘byType’
 Auto-wire a bean by property data type. In this case, since the data type of “person” bean is same as the data type of the “customer” bean’s property (Person object), so, Spring will auto wired it via setter method – “setPerson(Person person)“
 
 
 
4. Auto-Wiring ‘constructor’ 
Auto-wire a bean by property data type in constructor argument. In this case, since the data type of “person” bean is same as the constructor argument data type in “customer” bean’s property (Person object), so, Spring auto wired it via constructor method – “public Customer(Person person)“.

 
 
5. Auto-Wiring ‘autodetect’ 
If a default constructor is found, uses “constructor”; Otherwise, uses “byType”. In this case, since there is a default constructor in “Customer” class, so, Spring auto wired it via constructor method – “public Customer(Person person)“

 
 

@InitBinder - Custom Spring Validator to a Spring MVC Controller

0 comments

This technique should be used when you need to do ALL your controller’s validation yourself, and you can’t or don’t want to make use of the Hibernate’s reference implementation of a JSR 303 validator. From this, you’ll guess that you can’t mix your own custom Spring validator with Hibernate’s JSR 303 validator.


The MVC command object is a simple matter of tying together a few address fields:

public class Address {

  private String street;

  private String town;

  private String country;

  private String postCode;

  public String getStreet() {

    return street;
  }

  public void setStreet(String street) {

    this.street = street;
  }

  public String getTown() {

    return town;
  }

  public void setTown(String town) {

    this.town = town;
  }

  public String getCountry() {

    return country;
  }

  public void setCountry(String country) {

    this.country = country;
  }

  public String getPostCode() {

    return postCode;
  }

  public void setPostCode(String post_code) {

    this.postCode = post_code;
  }
}

Create a custom validator

@Component
public class AddressValidator implements Validator {

  /**
   * Return true if this object can validate objects of the given class. This is cargo-cult
   * code: all implementations are the same and can be cut 'n' pasted from earlier examples.
   */
  @Override
  public boolean supports(Class clazz) {

    return clazz.isAssignableFrom(Address.class);
  }

  /**
   * Validate an object, which must be a class type for which the supports() method returned
   * true.
   *
   * @param obj The target object to validate
   * @param errors contextual state info about the validation process (never null)
   */
  @Override
  public void validate(Object obj, Errors errors) {

    Address address = (Address) obj;
    String postCode = address.getPostCode();
    validatePostCode(postCode, errors);
  }

  private void validatePostCode(String postCode, Errors errors) {

    if (isValidString(postCode) && isNotBirminghamPostCode(postCode)) {
      errors.rejectValue("postCode", "AddressValidator.postCode.notBirmingham",
          "Not a Birmingham Post Code");
    }
  }

  private boolean isValidString(String str) {

    return isNotNull(str) && (str.length() > 0);
  }

  private boolean isNotNull(String postCode) {

    return postCode != null;
  }

  /** The first character of the Birmingham post code is 'B' */
  private boolean isNotBirminghamPostCode(String postCode) {

    char val = postCode.charAt(0);
    return val != 'B';
  }
}

Attaching the validator to the controller is pretty straight forward. The first step is to annotate the Address command object with @Valid:

 @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addAddress(@Valid Address address, BindingResult result, Model model) {




The second step is to inject the validator into the data binder:

@InitBinder
  protected void initBinder(WebDataBinder binder) {

    binder.setValidator(addressValidator);
  }

Adding these two code snippets together, the complete AddressController code looks like this:

@Controller
public class AddressController {

  private static final String FORM_VIEW = "address.page";

  private static final String PATH = "/address";

  @Autowired
  private AddressValidator addressValidator;

  /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String getCreateForm(Model model) {

    model.addAttribute(new Address());
    return FORM_VIEW;
  }

  /**
   * Attach the custom validator to the Spring context
   */
  @InitBinder
  protected void initBinder(WebDataBinder binder) {

    binder.setValidator(addressValidator);
  }

  /**
   * This is the handler method. Check for errors and proceed to the next view
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addAddress(@Valid Address address, BindingResult result, Model model) {

    if (!result.hasErrors()) {
      model.addAttribute("noErrors",
          "No Errors This Time for postal code: " + address.getPostCode());
    }

    return FORM_VIEW;
  }
}

Same Validation Using JSR 303 validator

public class Address {

  // These JSR 303 built in annotations don't do anything
  // When you've injected your own validator
  @NotEmpty
  @Size(min = 1, max = 12)
  private String street;

  @NotEmpty
  private String town;

  @NotEmpty
  private String country;

  @NotEmpty
  private String postCode;

Spring MVC’s @ModelAttribute Annotation

0 comments
The @ModelAttribute annotation is used as part of a Spring MVC web app and can be used in two scenarios.

  • Firstly, it can be used to inject data objects the model before a JSP loads. This makes it particularly useful in ensuring that a JSP has all the data is needs to display itself. The injection is achieved by binding a method return value to the model.
  • Secondly, it can be used to read data from an existing model assigning it to handler method parameters.

To demonstrate the @ModelAttributes, I'm using the simplest of scenarios: adding a user account to a hypothetical system and then, once the user account has been created, displaying the new user’s details on a welcome screen.

In order to start the ball rolling, I’ll need a simple User bean with some familiar fields: first name, last name, nick name and email address - the usual suspects.
public class User {

  private String firstName;

  private String lastName;

  private String nickName;

  private String emailAddress;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getNickName() {
    return nickName;
  }

  public void setNickName(String nickName) {
    this.nickName = nickName;
  }

  public String getEmailAddress() {
    return emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }
}

I’ll also need a Spring MVC controller to handle creating users. This will contains a couple of important methods that use the @ModelAttribute annotation, demonstrating the functionality outlined above.
 The method below demonstrates how to bind a method return value to a model.
/**
   * This creates a new User object for the empty form and stuffs it into
   * the model
   */
  @ModelAttribute("User")
  public User populateUser() {
    User user = new User();
    user.setFirstName("your first name");
    user.setLastName("your last name");
    return user;
  }

This method is called before every @RequestMapping annotated handler method to add an initial object to the model, which is then pushed through to the JSP. Notice the word every in the above sentence. The @ModelAttribute annotated methods (and you can have more than one per controller) get called irrespective of whether or not the handler method or JSP uses the data. In this example, the second request handler method call doesn’t need the new user in the model and so the call is superfluous. Bare in mind that this could possibly degrade application performance by making unnecessary database calls etc. It’s therefore advisable to use this technique only when each handler call in your Controller class needs the same common information adding to the model for every page request. In this example, it would be more efficient to write:



 /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String createForm() {

    populateUser();
    return FORM_VIEW;
  }
The method below demonstrates how to annotate a request method argument, so that data is extracted from the model and bound to the argument.
 /**
   * This is the handler method. Stick the user bean into a new attribute for
   * display on the next page
   *
   * @param user
   *            The user bean taken straight from the model
   * @param model
   *            An out param. Takes the user and adds it to the model FOR the
   *            NEXT page under a different name.
   *
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addUser(@ModelAttribute("user") User user,
      BindingResult result, Model model) {

    model.addAttribute("newUser", user);
    return WELCOME_VIEW;
  }
In this example, an ‘add user’ button on a form has been pressed calling the addUser() method. The addUser() method needs a User object from the incoming model, so that the new user’s details can be added to the database. The @ModelAttribute("user") annotation applied takes any matching object from the model with the “user” annotation and plugs it into the User user method argument.

Just for the record, this is the full controller code.

@Controller
public class AddUserController {

  private static final String FORM_VIEW = "adduser.page";

  private static final String WELCOME_VIEW = "newuser.page";

  private static final String PATH = "/adduser";

  /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String createForm() {

    return FORM_VIEW;
  }

  /**
   * This creates a new User object for the empty form and stuffs it into
   * the model
   */
  @ModelAttribute("User")
  public User populateUser() {
    User user = new User();
    user.setFirstName("your first name");
    user.setLastName("your last name");
    return user;
  }

  /**
   * This is the handler method. Stick the user bean into a new attribute for
   * display on the next page
   *
   * @param user
   *            The user bean taken straight from the model
   * @param model
   *            An out param. Takes the user and adds it to the model FOR the
   *            NEXT page under a different name.
   *
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addUser(@ModelAttribute("user") User user,
      BindingResult result, Model model) {

    model.addAttribute("newUser", user);
    return WELCOME_VIEW;
  }
}

Tuesday, 19 March 2013

Measuring elapsed time using Spring StopWatch

0 comments

Measuring elapsed time using Spring StopWatch

package Core;

import org.springframework.util.StopWatch;

public class ExecutionTimeStopWatch {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   StopWatch watch = new StopWatch();
   
   ExecutionTime obj = new ExecutionTime();
   watch.start();
   obj.method();
   watch.stop();
   System.out.println("Time Taken: "+ watch.getTotalTimeMillis());
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}



Thursday, 14 March 2013

Spring Bean Scopes

0 comments
Spring framework supports five type of scopes and for bean instantiation as of Spring 3.0 and also we can create a custom scope.
  1. singleton
  2. prototype
  3. request
  4. session
  5. global_session

1. singleton scope

singleton is the default scope.  Singleton Design Pattern requires no introduction as it is the easiest of all to understand. In the bean definition if the scope is not given, then by default singleton scope is assumed. In a given Spring container a singleton scoped bean
will be instantiated only once and the same will be used for its lifetime.
<bean id=zooEntity class=com.entities.Zoo
/>
<!-- if scope is not given, singleton is assigned as default scope, therefore both these configurations are same -->
<bean id=zooEntity class=com.entities.Zoo scope=singleton />

2. prototype scope

prototype scope allows the bean to be instantiated whenever it is requested. Every time a separate instance is created, just opposite to singleton. Stateful beans which hold the conversational state should be declared as prototype
scope.

3. request scope

Spring bean configured as request scope instantiates the bean for a single HTTP request. The instantiated object lives through the HTTP request. This is available only for web-aware spring application context.

4. session scope

session scope is very similar to  HttpSession Scope. Beans instantiated based on session scope scope lives through the HTTP session. Similar to request scope, it is applicable only for web aware spring application contexts.

5. global_session scope

global_session scope is equal as session scope on portlet-based web applications. This scope is also applicable only for web aware spring application contexts. If this is global_session is used in normal web application (not in portlet), then it will behave as session scope and there will not be any error.

Annotation based Spring scope configuration

/** * Annotation-based configuration of session scope */
@Component
@Scope("session")
public class ShopCart { }
Added to these built-in spring container scopes, we have an option to create custom scope. I will write a separate tutorial on spring custom scope.
Related Posts Plugin for WordPress, Blogger...