Spring in Action: A Spring Jump Start. Part 2 | 4

Spring in Action: A Spring Jump Start. Part 2

1.5.3 AOP in the enterprise

Enterprise applications often require certain services such as security and transactional support. One way of applying these services is to code support for them directly into the classes that use them. For example, to handle transactions, you may place the following snippet throughout your code:

The problem with handling transactions this way is that you may repeat the same transaction handling code several times—once for each time you need a transactional context. What's more, your application code is responsible for more than its core functionality.

EJB simplifies things by making it possible to declare these services and their policies in the EJB deployment descriptor. With EJB it is possible to write components that are ignorant of the fact that they are in a transactional context or being secured and then declare the transactional and security policies for those components in the EJB deployment descriptor. For example, to ensure that a method is transactional in EJB, you simply place the following in the deployment descriptor:

EJB has hung its hat on how it simplifies infrastructure logic such as transactions and security. But as we discussed in the introduction to this chapter, EJB has complicated matters in other ways.

Although Spring's AOP support can be used to separate cross-cutting concerns from your application's core logic, its primary job is as the basis for Spring's support for declarative transactions. Spring comes with several aspects that make it possible to declare transaction policies for JavaBeans. And the Acegi Security System (another open-source project associated with Spring) provides declarative security to JavaBeans. As with all Spring configuration, the transactional and security policies are prescribed in a Spring configuration file.

For example, suppose that instead of a knight your application handles student registration for training courses. Perhaps you have a bean called StudentServiceImpl that implements the following interface:

    public StudentService {
      public void registerForCourse(Student student, Course course);
    }

This bean may be registered in the Spring bean XML file as follows:

StudentService's registerForCourse() method should perform the following actions: