spring in action Third 2

1.1.3          Applying aspects

Aspect-oriented programming is often defined as a technique that promotes sepa- ration of concerns within a software system. Systems are composed of several compo- nents, each responsible for a specific piece of functionality. Often these components also carry additional responsibility beyond their core functionality. System services such as logging, transaction management, and security often find their way into components whose core responsibility is something else. These system services are commonly referred to as cross-cutting concerns because they tend to cut across multiple components in a system.

By spreading these concerns across multiple components, you introduce two levels of complexity to your code:

¡ The code that implements the systemwide concerns is duplicated across multi- ple components. This means that if you need to change how those concerns work, youll need to visit multiple components. Even if youve abstracted the concern to a separate module so that the impact to your components is a single method call, that method call is duplicated in multiple places.

¡ Your components are littered with code that isnt aligned with their core func- tionality. A method to add an entry to an address book should only be con- cerned with how to add the address and not with whether its secure or transactional.

AOP makes it possible to modularize these services and then apply them declaratively to the components that they should affect. This results in components that are more cohesive and that focus on their own specific concerns, completely ignorant of any sys- tem services that may be involved. In short, aspects ensure that POJOs remain plain. It may help to think of aspects as blankets that cover many components of an appli- cation, as illustrated in figure 1.3. At its core, an application consists of modules that implement business functionality. With AOP, you can then cover your core application with layers of functionality. These layers can be applied declaratively throughout your application in a flexible manner without your core application even knowing they

exist. This is a powerful concept, as it keeps the security, transaction, and logging con- cerns from littering the application’s core business logic.

AOP IN ACTION

To turn Minstrel into an aspect, all you need to do is declare it as one in the Spring configuration file. Here’s the updated knights.xml file, revised to declare Minstrel as an aspect.

Here you’re using Spring’s aop configuration namespace to declare that the Minstrel bean is an aspect. First, you had to declare the Minstrel as a bean. Then you refer to that bean in the <aop:aspect> element. Defining the aspect further, you declare (using <aop:before>) that before the embarkOnQuest() method is executed, the Min- strel’s singBeforeQuest() should be called. This is called before advice. And you (using <aop:after>) declare that the singAfterQuest() method should be called after embarkOnQuest() has executed. This is known as after advice. In both cases, the pointcut-ref attribute refers to a pointcut named embark. This pointcut is defined in the preceding <pointcut> element with an expression attri-bute set to select where the advice should be applied. The expression syntax is AspectJ’s pointcut expression language.

I should also point out that although you used some Spring magic to turn Min- strel into an aspect, it was declared as a Spring <bean> first. The point here is that you can do anything with Spring aspects that you can do with other Spring beans, such as injecting them with dependencies.

1.1.4         Eliminating boilerplate code with templates

What’s most notable about listing 1.11 is that much of it is the exact same code that you’d write for pretty much any JDBC operation. Little of it has anything to do with querying for an employee, and much of it is JDBC boilerplate.

JDBC’s not alone in the boilerplate code business. Many activities often require similar boilerplate code. JMS, JNDI, and the consumption of REST services often involve a lot of commonly repeated code.

Spring seeks to eliminate boilerplate code by encapsulating it in templates. Spring’s JdbcTemplate makes it possible to perform database operations without all of the ceremony required by traditional JDBC. For example, using Spring’s SimpleJdbcTemplate (a specialization of Jdbc- Template that takes advantage of Java 5 features), the getEmployeeById() method can be rewritten so that its focus is on the task of retrieving employee data and not catering to the demands of the JDBC API. The following shows what such an updated getEmployeeById() method might look like.

I’ve shown you how Spring attacks complexity in Java development using POJO-oriented development, dependency injection, AOP, and templates. Along the way I showed you how to configure beans and aspects in XML-based configuration files. But how do those files get loaded? And what are they loaded into? Let’s look at the Spring container, the place where your application’s beans will reside.

1.2    Containing your beans

In a Spring-based application, your application objects will live within the Spring con- tainer. As illustrated in figure 1.4, the container will create the objects, wire them together, configure them, and manage their complete lifecycle from cradle to grave (or new to finalize(), as the case may be).

The container is at the core of the Spring Framework. Spring’s container uses dependency injection (DI) to manage the components that make up an application. This includes creating associations between collaborating components. As such, these objects are cleaner and easier to understand, support reuse, and are easy to unit test.

There’s no single Spring container. Spring comes with several container implementa- tions that can be categorized into two distinct types. Bean factories (defined by the org.springframework.beans.factory.BeanFactory interface) are the simplest of containers, providing basic support for DI. Application contexts (defined by the org.springframework.context.ApplicationContext interface) build on the notion of a bean factory by providing application framework services, such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.

1.2.1           Working with an application context

Spring comes with several flavors of application context. The three that youll most likely encounter are

¡ ClassPathXmlApplicationContext-Loads a context definition from an XML file located in the classpath, treating context definition files as classpath resources. ¡ FileSystemXmlApplicationContext-Loads a context definition from an XML file in the file system.

¡ XmlWebApplicationContext-Loads context definitions from an XML file con-tained within a web application.

The difference between using FileSystemXmlApplicationContext and ClassPath- XmlApplicationContext is that FileSystemXmlApplicationContext will look for foo.xml in a specific location within the file system, whereas ClassPathXml- ApplicationContext will look for foo.xml anywhere in the classpath (including JAR files).

1.2.2           A bean’s life

In contrast, the lifecycle of a bean within a Spring container is more elaborate. It’s important to understand the lifecycle of a Spring bean, because you may want to take advantage of some of the opportunities that Spring offers to customize how a bean is created. Figure 1.5 shows the startup lifecycle of a typical bean as it’s loaded into a Spring application context.

As you can see, a bean factory performs several setup steps before a bean is ready to use. Breaking down figure 1.5 in more detail:

1 Spring instantiates the bean.

2 Spring injects values and bean references into the bean’s properties.

3 If the bean implements BeanNameAware, Spring passes the bean’s ID to the set- BeanName() method. 4 If the bean implements BeanFactoryAware, Spring calls the setBeanFactory() method, passing in the bean factory itself.

5If the bean implements ApplicationContextAware, Spring will call the set- ApplicationContext() method, passing in a reference to the enclosing appli- cation context.

6If any of the beans implement the BeanPostProcessor interface, Spring calls their postProcessBeforeInitialization() method.

7If any beans implement the InitializingBean interface, Spring calls their afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method will be called.

8 If there are any beans that implement BeanPostProcessor, Spring will call their postProcessAfterInitialization() method.

9At this point, the bean is ready to be used by the application and will remain in the application context until the application context is destroyed.

10 If any beans implement the DisposableBean interface, then Spring will call their destroy() methods. Likewise, if any bean was declared with a destroy- method, then the specified method will be called.

1.3    Surveying the Spring landscape

1.3.1          Spring modules

The Spring Framework is composed of several distinct modules. When you download and unzip the Spring Framework distribution, you’ll find 20 different JAR files in the dist directory, as shown in figure 1.6. The 20 JAR files that make up Spring can be arranged in one of six different cate- gories of functionality, as illustrated in figure 1.7.

CORE SPRING CONTAINER

In addition to the bean factory and application context, this module also supplies many enterprise services such as email,JNDI access, EJB integration, and scheduling.

As you can see, all of Spring’s modules are built on top of the core container. You’ll implicitly use these classes when you configure your application.

SPRING’S AOP MODULE

Spring provides rich support for aspect-oriented programming in its AOP module. This module serves as the basis for developing your own aspects for your Spring- enabled application.

DATA ACCESS AND INTEGRATION

Spring’s JDBC and data access objects (DAO) module abstracts away the boilerplate code so that you can keep your database code clean and simple, and prevents problems that result from a failure to close database resources. Spring’s JDBC and data access objects (DAO) module abstracts away the boilerplate code so that you can keep your database code clean and simple, and prevents problems that result from a failure to close database resources.

Spring’s JDBC and data access objects (DAO) module abstracts away the boilerplate code so that you can keep your database code clean and simple, and prevents problems that result from a failure to close database resources.

WEB AND REMOTING

Even though Spring integrates with several popular MVC frameworks, its web and remoting module comes with a capable MVC framework that promotes Springs loosely coupled techniques in the web layer of an application. This framework comes in two forms: a servlet-based framework for conventional web applications and a portlet-based application for developing against the Java portlet API.

In addition to user-facing web applications, this module also provides several remoting options for building applications that interact with other applications. Springs remoting capabilities include Remote Method Invocation (RMI), Hessian, Burlap, JAX-WS, and Springs own HTTP invoker.

TESTING

Within this module you’ll find a collection of mock object implementations for writing unit tests against code that works with JNDI, servlets, and portlets. For integra- tion-level testing, this module provides support for loading a collection of beans in a Spring application context and working with the beans in that context.

1.3.2          The Spring portfolio

1.4    What’s new in Spring

1.4.1          What’s new in Spring 2.5?

In November 2007, the Spring team released version 2.5 of the Spring Framework. The significance of Spring 2.5 was that it marked Spring’s embrace of annotation- driven development. Prior to Spring 2.5, XML-based configuration was the norm. But Spring 2.5 introduced several ways of using annotations to greatly reduce the amount of XML needed to configure Spring:

l  Annotation-driven dependency injection through the @Autowired annotation and fine-grained auto-wiring control with @Qualifier.

l  Support for JSR-250 annotations, including @Resource for dependency injec- tion of a named resource, as well as @PostConstruct and @PreDestroy for life- cycle methods.

l  Auto-detection of Spring components that are annotated with @Component (or one of several stereotype annotations).

l  An all-new annotation-driven Spring MVC programming model that greatly sim- plifies Spring web development.

l   A new integration test framework thats based on JUnit 4 and annotations.

Even though annotations were the big story of Spring 2.5, there’s more:

l  Full Java 6 and Java EE 5 support, including JDBC 4.0, JTA 1.1, JavaMail 1.4, and JAX-WS 2.0.

l  A new bean-name pointcut expression for weaving aspects into Spring beans by their name.

l  Built-in support for AspectJ load-time weaving.

l  New XML configuration namespaces, including the context namespace for configuring application context details and a jms namespace for configuring message-driven beans.

l  Support for named parameters in SqlJdbcTemplate.

1.4.2          What’s new in Spring 3.0?

With all of the good stuff in Spring 2.5, it’s hard to imagine what could possibly follow in Spring 3.0. But with the 3.0 release, Spring one-upped itself with the continuation of the annotation-driven theme and several new features:

l  Full-scale REST support in Spring MVC, including Spring MVC controllers that respond to REST-style URLs with XML, JSON, RSS, or any other appropriate response. Well look into Spring 3s new REST support in chapter 11.

l  A new expression language that brings Spring dependency injection to a new level by enabling injection of values from a variety of sources, including other beans and system properties. Well dig into Springs expression language in the next chapter.

l  New annotations for Spring MVC, including @CookieValue and @Request- Header, to pull values from cookies and request headers, respectively. Well see how to use these annotations as we look at Spring MVC in chapter 7.

l  A new XML namespace for easing configuration of Spring MVC.

l  Support for declarative validation with JSR-303 (Bean Validation) annotations.

l  Support for the new JSR-330 dependency injection specification.

l  Annotation-oriented declaration of asynchronous and scheduled methods.

l  A new annotation-based configuration model that allows for nearly XML-free Spring configuration. Well see this new configuration style in the next chapter.

l  The Object-to-XML (OXM) mapping functionality from the Spring Web Ser- vices project has been moved into the core Spring Framework.

1.4.3          What’s new in the Spring portfolio?

l  Spring Web Flow 2.0 was released with a simplified flow definition schema, mak-ing it even easier to create conversational web applications.

l  With Spring Web Flow 2.0 came Spring JavaScript and Spring Faces. Spring JavaScript is a JavaScript library that enables progressive enhancement of web pages with dynamic behavior. Spring Faces allows use of JSF as a view technology within Spring MVC and Spring Web Flow.

l  The old Acegi Security framework was completely overhauled and released as Spring Security 2.0. In this new incarnation, Spring Security offers a new configu- ration schema that dramatically reduces the amount of XML required to config- ure application security.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值