• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

New Features in Spring 2.5

December 22, 2008 //  by Krishna Srinivasan//  Leave a Comment

Introduction

This article provides a basic introduction to the new features that are available in Spring 2.5. This article provides no aim in explaining about the fundamentals of Spring framework as well as the related theories. For a more fundamental understanding, refer Introduction to Spring. The article initially begins by explaining about the common annotations like @Autowired, @Resource, @PostConstruct, @PreDestroy that were introduced as part of moving the configuration details from xml to Annotation. This is then followed by Auto-detection of classes and the set of annotations that were introduced in Spring MVC for simplifying web development have also been covered.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

If you are beginner for spring framework, please read our article on introduction to spring framework, spring aop, spring mvc and list of spring articles. Javabeat covers extensive articles on the spring framework. If you are interested in receiving the updates, please subscribe here.

New features in Spring 2.5

This section will cover the important new features that were introduced in Spring 2.5. More specifically, the following features were covered,

  • Configurations through Annotations
  • Auto Detection of components
  • Annotations on Web MVC

Configurations through Annotations

AutoWired and Resource Annotation

Wiring is the process of establishing linkage between two components and it is the responsibility of the developer to make this association to happen. Auto-wiring is the process of establishing linkage between components with the help of Spring Container without the intervention of developer. Auto-wiring can be done either by type or by name. Wiring and Auto-wiring features are available before Spring 2.5 itself. In 2.5, the Auto-wiring feature has been enhanced in such a way that a property can be auto-wired through a setter method, through any method and through constructor using @AutoWired annotation.
Let us look into an example. Assume that PrinterService is dependant on FileService for reading the contents of a file before printing. The interface and class declaration for FileService and FileServiceImpl are given below.
FileService.java

package net.javabeat.spring.newfeatures.autowire;

import java.io.IOException;

public interface FileService {

    String readFileContents(String fileName) throws IOException;

}

FileServiceImpl.java

package net.javabeat.spring.newfeatures.autowire;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileServiceImpl implements FileService{

    public String readFileContents(String fileName) throws IOException {

        StringBuilder contents = new StringBuilder();
        FileReader fReader = null;
        BufferedReader bReader = null;

        try{
            fReader = new FileReader(fileName);
            bReader = new BufferedReader(fReader);

            while (true){

                String line = bReader.readLine();
                if (line == null){
                    break;
                }
                contents.append(line);
           }
        }
        catch (IOException exception){
            throw exception;
        }
        finally{
            if (bReader != null){
                bReader.close();
            }
            if (fReader != null){
                fReader.close();
            }
        }
        return contents.toString();
    }
}

Now, let us look into the PrinterService interface that makes use of FileService. Since PrinterService depends on FileService, an instance of FileService object has to be auto-wired against the PrinterService object. Let us see the implementation for PrinterService class,
PrinterService.java

package net.javabeat.spring.newfeatures.autowire;

public interface PrinterService {

    void print(String fileName);

}

PrinterServiceImpl.java

package net.javabeat.spring.newfeatures.autowire;

import java.io.IOException;

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

public class PrinterServiceImpl implements PrinterService {

    @Autowired
    private FileService fileService;

    public PrinterServiceImpl() {}

    public PrinterServiceImpl(FileService fileService){
        this.fileService = fileService;
    }

    public void print(String fileName){
        try {
            String contents = fileService.readFileContents(fileName);
            System.out.println("Printing " + fileName + "with contents " + contents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Note that we have used @AutoWired annotation directly at the property level for the FileService object. That’s not the end of the whole story. To provide an indication to the Spring Container that we are making use of autowiring annotation, we have to declare <context:annotation-config /&gt; in the configuration file. Let us have a look into the following configuration file,
autowire.xml

&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

&lt;context:annotation-config /&gt;

&lt;bean id=&quot;fileService&quot;
&gt;
&lt;/bean&gt;

&lt;bean id=&quot;printerService&quot;
&gt;
&lt;/bean&gt;

&lt;/beans&gt;

The annotations @AutoWired and @Resource have the same purpose, the only difference being, for @AutoWired the injection happens through type and for @Resource, the injection happens through name,

@Resource(name=&quot;fileService&quot;)
private FileService fileService;

@PostConstruct and @PreDestroy annotations

The annotations @PostConstruct and @PreDestroy serve the same purpose of the initialization and the destruction lifecycle callbacks that were available in the earlier versions of Spring. The following class, MyResource makes use of @PostConstruct and @PreDestroy annotations,
MyResource.java

package net.javabeat.spring.newfeatures.prepost;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyResource {

    @PostConstruct
    public void afterOpen(){
        System.out.println(&quot;Resource after open...&quot;);
    }

    @PreDestroy
    public void beforeClose(){
        System.out.println(&quot;Resource before close...&quot;);
    }
}

As before, as a way of indication to Spring framework, the configuration file should have the entry <context:annotation-config />, that is declared below,
prepost.xml

&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

&lt;context:annotation-config /&gt;

&lt;bean id=&quot;myResource&quot;
&gt;
&lt;/bean&gt;

&lt;/beans&gt;

In a typical Spring Application, developer will create a bunch of classes and makes association between them by configuring them in the xml file. This often seems to be repetitive and Spring provides a way for automatically detecting such classes when the classes are made visible to the Spring Container in the application’s classpath. This feature is called auto-detection of classes/components in the class path. For this to happen, the classes have to be exposed as components so that the Spring Framework can auto detect them. The annotations @Component, @Service and @Respository are available to achieve this auto-detection of components. Note that any class can be designated as a component and the annotations @Service and @Respository are specialized forms of components.
Let us look into an example of the EmployeeService class that makes use of EmployeeDao for fetching Employee objects. In this case, the class Employee can be designated with @Component annotation. Since the EmployeeService is a service class for the clients for fetching employee objects, this class can be modeled with @Service annotation. The EmployeeDao class is quite different here, a real implementation would hit the database repository for querying the employee objects that would be ultimately returned to the client application through the EmployeeService class, this class can be decorated with @Repository annotation.
Look into the following class declaration for Employee with @Component annotation,

package net.javabeat.spring.newfeatures.componentscanning;

import org.springframework.stereotype.Component;

@Component
public class Employee {

    private String name;
    private int age;
    private int id;

    public Employee() {}

    public Employee(String name, int age, int id){
        this.name = name;
        this.age = age;
        this.id = id;
    }

    public String getName(){
        return name;
    }

    public int getAge(){
        return age;
    }

    public int getId(){
        return id;
    }
}

The declaration of EmployeeDao class which is decorated with @Repository annotation is given below,
EmployeeDao.java

package net.javabeat.spring.newfeatures.componentscanning;

public interface EmployeeDao {

    Employee getEmployee(int id);

}

EmployeeDaoImpl.java

package net.javabeat.spring.newfeatures.componentscanning;

import java.util.Map;

import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDaoImpl implements EmployeeDao{

    private Map employees;

    public EmployeeDaoImpl(){

        employees.put(100, new Employee(&quot;X&quot;, 25, 100));
        employees.put(200, new Employee(&quot;Y&quot;, 35, 200));
        employees.put(300, new Employee(&quot;Z&quot;, 45, 300));
    }

    public Employee getEmployee(int id) {
        return employees.get(id);
    }
}

Even though a real implementation of EmployeeDao class would be making use of JdbcTemplate for hitting the database, since the example is provided only for illustration purpose, the implementation just maintains a map of employees and will return an employee object based on the employee id.
Finally comes the client-facing EmployeeService class, also note that the property employeeDao is autowired which is given below,
EmployeeService.java

package net.javabeat.spring.newfeatures.componentscanning;

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

@Service
public class EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    public EmployeeService(EmployeeDao employeeDao){
        this.employeeDao = employeeDao;
    }

    public Employee getEmployee(int employeeId){
        return employeeDao.getEmployee(employeeId);
    }
}

The annotations @Component, @Repostitory and @Service are also referred to as stereotype annotations and the Spring framework has to be instructed for the scanning of classes by specifying it through a special element in the xml configuration, where the value for the element is a list of packages separated by comma as below,

&lt;context:component-scan
base-package=&quot; net.javabeat.spring.newfeatures.componentscanning&quot; /&gt;

Annotations on Web MVC

Controller Annotation

The @Controller annotation can be applied to any class that wants to act as a web controller in the web application context. In the previous versions of Spring, a controller class will make made to extend Spring specific base controller, thereby making it hard to perform unit testing. Now, the controller is a POJO class, just annotated with @Controller class, also note that @Controller is a class level annotation and it cannot be applied at the method level. Look into the following example,
PageController.java

package net.javabeat.spring.newfeatures.mvc;

import org.springframework.stereotype.Controller;

@Controller
public class PageController {

}

RequestMapping Annotation

The request mapping annotation, as designated by @RequestMapping can be used in a variety of ways. This annotation can be used at the class level as well as with the method level. Let us see an example usage case for the @RequestMapping annotation, where a particular URL is directly mapped to a Controller class and the type of request for the URL is mapped to the handler methods available within the Controller class,
HelloController.java

package net.javabeat.spring.newfeatures.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;

@Controller
@RequestMapping(value = &quot;/hello.html&quot;)
public class HelloController {

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView forGetAndPostRequest(){

        ModelAndView modelAndView = null;
        // Populate the modelAndView object before return.
        return modelAndView;
    }
}

In the above class, as a way of providing indication to the Spring framework that HelloController is a web controller, we have decorated it with the @Controller annotation. Secondly we have directly mapped the URL /hello.html to this Controller class. Additionally, we have also specified that the GET and POST request types should be handled by the method forGetAndPostRequest as designated by the @RequestMapping annotation.

Conclusion

This article covered the list of new annotations that were introduced for auto-wiring components as well as to model the life cycle methods that can happen during construction and destruction of beans. Spring 2.5 has made the life for a developer more easier than before, with the bunch of Annotations and more specifically with the auto-detection of components feature in the classpath, there is no need to provide manual configuration information in the xml file. The annotations that were introduced in the web tier have further simplified the developmental effort of Web applications.

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

If you have any questions on the spring framework integration with email, please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring framework, interview questions, spring and hibernate integration,etc.
If you would like to receive the future java articles from our website, please subscribe here.

Category: Spring FrameworkTag: Spring 2.5

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « What is RSS and Atom?
Next Post: New Features in Servlets 3.0 »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact