JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

32
JBoss Web Framework Kit 1.1 Snowdrop Sportsclub Example Integrating Spring with the JBoss Enterprise Platforms Marius Bogoevici

Transcript of JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Page 1: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

JBoss WebFramework Kit 1.1

SnowdropSportsclub Example

Integrating Spring with the JBoss Enterprise Platforms

Marius Bogoevici

Page 2: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Snowdrop Sportsclub Example

JBoss Web Framework Kit 1.1 Snowdrop Sportsclub ExampleIntegrating Spring with the JBoss Enterprise PlatformsEdition 1.0

Author Marius Bogoevici [email protected] Laura Bailey [email protected] Rebecca Newton [email protected]

Copyright © 2010 Red Hat, Inc.

The text of and illustrations in this document are licensed by Red Hat under a Creative CommonsAttribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is availableat http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute thisdocument or an adaptation of it, you must provide the URL for the original version.

Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert,Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.

Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, MetaMatrix, Fedora, the InfinityLogo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.

Linux® is the registered trademark of Linus Torvalds in the United States and other countries.

Java® is a registered trademark of Oracle and/or its affiliates.

XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United Statesand/or other countries.

MySQL® is a registered trademark of MySQL AB in the United States, the European Union and othercountries.

All other trademarks are the property of their respective owners.

This book provides a walkthrough of the JBoss Snowdrop Sportsclub example. It illustrates severaluse cases for integrating the JBoss Enterprise Platforms with the Spring Framework.

Page 3: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

iii

Preface v1. Document Conventions ................................................................................................... v

1.1. Typographic Conventions ...................................................................................... v1.2. Pull-quote Conventions ........................................................................................ vi1.3. Notes and Warnings ............................................................................................ vii

2. We Need Feedback! ...................................................................................................... vii

1. Introduction 11.1. Prerequisites ................................................................................................................ 1

1.1.1. Download the Example ...................................................................................... 11.1.2. Setting up Maven repositories ............................................................................ 1

1.2. How to build and run the examples ............................................................................... 21.2.1. Building the application ...................................................................................... 21.2.2. Initializing the database ..................................................................................... 21.2.3. Preparing your JBoss Enterprise Platform ........................................................... 31.2.4. Deploying the application ................................................................................... 31.2.5. Starting the database ........................................................................................ 31.2.6. Special configuration for distinct profiles .............................................................. 4

1.3. Sportsclub and JBoss Developer Studio ........................................................................ 4

2. Understanding the application structure 52.1. The application structure and its use cases ................................................................... 52.2. A comparative look of the project modules .................................................................... 6

3. Using JBoss and Spring together 73.1. A look at the JBoss/Spring integration use cases ........................................................... 73.2. The domain model ....................................................................................................... 93.3. Persistence implementation: JPA and Hibernate ........................................................... 10

3.3.1. The Hibernate implementation .......................................................................... 103.3.2. The JPA implementation .................................................................................. 113.3.3. Unit testing the repositories .............................................................................. 12

3.4. Service Layer ............................................................................................................. 123.4.1. The Spring-based service layer ........................................................................ 133.4.2. The EJB service layer ...................................................................................... 13

3.5. Presentation Layer ..................................................................................................... 143.5.1. Subscriptions: JSF and Spring ......................................................................... 143.5.2. Reservations: JSF/Spring integration ................................................................ 143.5.3. Invoicing: Spring MVC and EJB ........................................................................ 163.5.4. A problem of reusing content ........................................................................... 18

3.6. Enterprise Integration Features ................................................................................... 183.6.1. Payment processing: JMS integration through JCA ............................................ 183.6.2. Aspects and auditing ....................................................................................... 203.6.3. Configuring Spring beans through JMX ............................................................. 203.6.4. Payment processing: exposing a JAX-WS web service ....................................... 21

A. Revision History 23

Page 4: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

iv

Page 5: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

v

Preface

1. Document ConventionsThis manual uses several conventions to highlight certain words and phrases and draw attention tospecific pieces of information.

In PDF and paper editions, this manual uses typefaces drawn from the Liberation Fonts1 set. TheLiberation Fonts set is also used in HTML editions if the set is installed on your system. If not,alternative but equivalent typefaces are displayed. Note: Red Hat Enterprise Linux 5 and later includesthe Liberation Fonts set by default.

1.1. Typographic ConventionsFour typographic conventions are used to call attention to specific words and phrases. Theseconventions, and the circumstances they apply to, are as follows.

Mono-spaced Bold

Used to highlight system input, including shell commands, file names and paths. Also used to highlightkeycaps and key combinations. For example:

To see the contents of the file my_next_bestselling_novel in your currentworking directory, enter the cat my_next_bestselling_novel command at theshell prompt and press Enter to execute the command.

The above includes a file name, a shell command and a keycap, all presented in mono-spaced boldand all distinguishable thanks to context.

Key combinations can be distinguished from keycaps by the hyphen connecting each part of a keycombination. For example:

Press Enter to execute the command.

Press Ctrl+Alt+F2 to switch to the first virtual terminal. Press Ctrl+Alt+F1 toreturn to your X-Windows session.

The first paragraph highlights the particular keycap to press. The second highlights two keycombinations (each a set of three keycaps with each set pressed simultaneously).

If source code is discussed, class names, methods, functions, variable names and returned valuesmentioned within a paragraph will be presented as above, in mono-spaced bold. For example:

File-related classes include filesystem for file systems, file for files, and dir fordirectories. Each class has its own associated set of permissions.

Proportional Bold

This denotes words or phrases encountered on a system, including application names; dialog box text;labeled buttons; check-box and radio button labels; menu titles and sub-menu titles. For example:

Choose System → Preferences → Mouse from the main menu bar to launch MousePreferences. In the Buttons tab, click the Left-handed mouse check box and click

1 https://fedorahosted.org/liberation-fonts/

Page 6: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Preface

vi

Close to switch the primary mouse button from the left to the right (making the mousesuitable for use in the left hand).

To insert a special character into a gedit file, choose Applications → Accessories→ Character Map from the main menu bar. Next, choose Search → Find… from theCharacter Map menu bar, type the name of the character in the Search field and clickNext. The character you sought will be highlighted in the Character Table. Double-click this highlighted character to place it in the Text to copy field and then click the

Copy button. Now switch back to your document and choose Edit → Paste from thegedit menu bar.

The above text includes application names; system-wide menu names and items; application-specificmenu names; and buttons and text found within a GUI interface, all presented in proportional bold andall distinguishable by context.

Mono-spaced Bold Italic or Proportional Bold Italic

Whether mono-spaced bold or proportional bold, the addition of italics indicates replaceable orvariable text. Italics denotes text you do not input literally or displayed text that changes depending oncircumstance. For example:

To connect to a remote machine using ssh, type ssh [email protected] ata shell prompt. If the remote machine is example.com and your username on thatmachine is john, type ssh [email protected].

The mount -o remount file-system command remounts the named filesystem. For example, to remount the /home file system, the command is mount -oremount /home.

To see the version of a currently installed package, use the rpm -q packagecommand. It will return a result as follows: package-version-release.

Note the words in bold italics above — username, domain.name, file-system, package, version andrelease. Each word is a placeholder, either for text you enter when issuing a command or for textdisplayed by the system.

Aside from standard usage for presenting the title of a work, italics denotes the first use of a new andimportant term. For example:

Publican is a DocBook publishing system.

1.2. Pull-quote ConventionsTerminal output and source code listings are set off visually from the surrounding text.

Output sent to a terminal is set in mono-spaced roman and presented thus:

books Desktop documentation drafts mss photos stuff svnbooks_tests Desktop1 downloads images notes scripts svgs

Source-code listings are also set in mono-spaced roman but add syntax highlighting as follows:

package org.jboss.book.jca.ex1;

import javax.naming.InitialContext;

Page 7: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Notes and Warnings

vii

public class ExClient{ public static void main(String args[]) throws Exception { InitialContext iniCtx = new InitialContext(); Object ref = iniCtx.lookup("EchoBean"); EchoHome home = (EchoHome) ref; Echo echo = home.create();

System.out.println("Created Echo");

System.out.println("Echo.echo('Hello') = " + echo.echo("Hello")); }}

1.3. Notes and WarningsFinally, we use three visual styles to draw attention to information that might otherwise be overlooked.

Note

Notes are tips, shortcuts or alternative approaches to the task at hand. Ignoring a note shouldhave no negative consequences, but you might miss out on a trick that makes your life easier.

Important

Important boxes detail things that are easily missed: configuration changes that only apply tothe current session, or services that need restarting before an update will apply. Ignoring a boxlabeled 'Important' will not cause data loss but may cause irritation and frustration.

Warning

Warnings should not be ignored. Ignoring warnings will most likely cause data loss.

2. We Need Feedback!If you find a typographical error in this manual, or if you have thought of a way to make this manualbetter, we would love to hear from you! Please submit a report in JIRA: http://jira.jboss.org/ against theproduct JBoss Enterprise Application Platform and component Documentation.

When submitting a bug report, be sure to mention the manual's identifier: JBoss Web Framework KitSnowdrop Sportsclub Example.

If you have a suggestion for improving the documentation, try to be as specific as possible whendescribing it. If you have found an error, please include the section number and some of thesurrounding text so we can find it easily.

Page 8: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

viii

Page 9: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 1.

1

IntroductionThe Sportsclub application provides a real world-inspired example of integrating Spring with theJBoss Entprise Platforms. It consists of three web applications, which illustrate several use casesthrough various combinations of components and technologies. It also illustrates how to use theSnowdrop libraries to provide JBoss-specific features, such as creating a standalone deployment of anApplicationContext and injecting beans from that application context into non-Spring componentslike Enterprise Java Beans (EJB).

This book aims to illustrate the mechanics of using Spring with different Java EE 5 components in thespecific context of the JBoss Enterprise Platforms, and to recommend methods of achieving certainintegration goals.

The Sportsclub example is not intended as a guide to creating a domain model. Detailing the variouslayers of application and UI design is outside the scope of this document. As such, the exampleapplication has been designed to illustrate integration use cases, rather than to demonstrate a domainmodel that strictly follows principles of object-oriented and domain-driven design.

The Sportsclub example uses RichFaces as a component library for JavaServer Faces (JSF). Consultthe RichFaces documentation for RichFaces-specific information.

1.1. PrerequisitesYou will need to install the following before you can run the Sportsclub example:

• Java 6 JDK

• A JBoss Enterprise Platform (JBoss Enterprise Application Platform 5.0 or later, or JBoss EnterpriseWeb Platform 5.0 or later)

• Maven 2.0.9 or later, with properly set up repositories

• the Snowdrop Spring deployer (see the Snowdrop User Guides for assistance)

1.1.1. Download the ExampleYou can download jboss-wfk-demo-1.1.0.zip from the Customer Support Portal.

1.1.2. Setting up Maven repositoriesThe Maven project setup does not assume a location for the artifacts used in the project becauseusers may have different settings for their Maven repositories (direct access to communityrepositories, proxies, enterprise repository with approved artifacts, etc.) so the user is responsible forrepository setup.

This example can be built out of the box if the settings.xml file for the local Maven installationenables the repositories from Maven Central and JBoss Releases. Instructions for setting up theJBoss Releases repository can be found at http://community.jboss.org/wiki/MavenGettingStarted-Users.

The pom.xml file can be modified to include references to other repositories, or equivalent artifactversions (if the build environment uses an enterprise-wide repository in which the artifacts havedifferent version numbers).

Page 10: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 1. Introduction

2

1.2. How to build and run the examplesBefore we detail the application structure and its use cases, let's run the application.

Running the application involves:

• Building the application

• Initializing the database

• Preparing your JBoss Enterprise Platform

• Deploying the application

• Starting the database

• Starting the application server

Below are some details on how to perform some of these steps.

1.2.1. Building the applicationIn this step we are building the application. The Sportsclub example uses Maven, so it can be built bysimply running:

mvn clean package

This will produce two EAR files, both named sportsclub.ear, located under sportsclub-ear/target and sportsclub-jpa-ear/target. They have the same functionality, but the underlyingimplementation of the persistence layer is different (one is using Hibernate, and another one usesJPA).

Important

The built application can use one of two main profiles:

spring-2.5The default. A Spring 2.5 variant of the application.

spring-3A Spring 3.0 variant of the application.

To build the Spring 3.0 variant of the application, use the following command:

mvn clean package -Pspring-3

1.2.2. Initializing the databaseThe application uses a standalone HSQLDB database, which needs to be initialized and started beforethe application is deployed. This section covers how to initialize (or reset) the database. Starting thedatabase is covered under deploying the application.

The database is initialized using maven:

cd databasemvn -Pdb-setup

Page 11: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Preparing your JBoss Enterprise Platform

3

Once this step has been completed, it does not need to be repeated again before running theapplication, but it can be repeated if the database needs to be reset.

1.2.3. Preparing your JBoss Enterprise PlatformBesides building the application and initializing the database, you need to set up your JBossEnterprise Platform to run your application. This step involves:

• setting up the Spring deployer

• creating a managed DataSource to access the database

• creating a Destination for JMS-related features

As explained in the prerequisites, the Spring deployer will be set up by extracting it into the$JBOSS_HOME/servers/$PROFILE/deployers directory. Please refer to the Spring deployersection of the Snowdrop User Guides for details.

To create the DataSource and the Destination, you need to use the facilities provided in thejbossconf directory.

cd jbossconf

Modify the jbossconf/jbossas.properties file to indicate the correct location of the JBoss AS installation.A commented example is provided.

mvn -Pinstall

This will copy the DataSource and JMS destination definitions into the JBoss server. Like the previousone, this step needs to be executed only once.

1.2.4. Deploying the applicationCopy one of the two EARs produced by the build to the deploy folder of your JBoss EnterprisePlatform: $JBOSS_HOME/server/default/deploy. The two alternative build files are:

• sportsclub-ear/target/sportsclub.ear (Hibernate-based implementation)

• sportsclub-jpa-ear/target/sportsclub.ear (JPA-based implementation, using Hibernateas the underlying provider).

1.2.5. Starting the databaseMove to the database directory:

cd database

Execute one of the two startup scripts:

• On Linux and other Unix-like systems:

./startdb.sh

• On Windows:

Page 12: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 1. Introduction

4

startdb.bat

The database must be always started before the application server is started and the application isdeployed. The application can also be deployed in a running application server (for example aftermaking changes to it), but this should always happen while the database is started.

1.2.6. Special configuration for distinct profilesThe Sportsclub application can be deployed in different JBoss Application Server profiles. Someof these profiles, like for example the Web profile, do not include a message broker, therefore JMSintegration features (see dedicated section) must be disabled. In order to disable JMS integration inthe Sportsclub application, the file sportsclub-invoicing-webmvc/src/main/webapp/WEB-INF/spring-business-context.xml must be modified by commenting out the following line:

<import resource="spring-messaging-context.xml"/>

Uncommenting the line will re-enable the JMS integration features.

1.3. Sportsclub and JBoss Developer StudioThe easiest way to understand how the application works is by looking at its sources. This guide willshow you how you can import the application into JBoss Developer Studio.

Sportsclub is Maven-based, so you will need to create the Eclipse project structure for it. You can dothis with the Maven Eclipse plugin:

mvn eclipse:eclipse -Dwtpversion=2.0

Alternately, you can install the m2eclipse Maven Eclipse plugin, and use it to import the application.

Page 13: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 2.

5

Understanding the applicationstructureThis chapter describes the business use cases covered by the application, and how the functionality isdistributed across the modules.

2.1. The application structure and its use casesThe Sportsclub example consists of three different applications sharing the same domain model,packaged and deployed together. This is done for simplicity reasons, but also to demonstrate a fewdifferent technologies and configuration options working side by side.

The application supports the following scenarios:

• maintaining information about subscribers, creating new subcriptions and closing existing accounts;

• creating, modifying and removing equipment reservations for subscribers;

• viewing the current balance of an account, issuing invoices for accounts that do not have a currentinvoice and updating the account whenever a payment has been received.

Each of these scenarios is covered by a separate web application, and all three applications arepackaged in a single EAR file.

Figure 2.1, “Structure of the Sportsclub application” shows how the application is structured:

Figure 2.1. Structure of the Sportsclub application

All three applications share a common domain model and a common DAO/repository layer,implemented using Spring. The application includes both Hibernate and JPA implementations forthe repository layer (using the Hibernate and JPA support provided by JBoss AS, respectively).The application is built in two different variants, each using one of the two DAO implementationalternatives.

Apart from that, each web application uses a different combination of technologies, illustrating one ormore integration use cases.

The Subscriptions application uses an EJB-based service layer and a JSF-based front-end, usingRichfaces components.

The Reservations application uses a Spring-based business layer and a JSF-based front-end, alsousing Richfaces components.

Page 14: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 2. Understanding the application structure

6

The Invoicing application uses an EJB service layer and a Spring MVC-based front-end (using JSPand Spring form tags). It also demonstrates the creation of JAX-WS based web services injected withSpring beans, JCA-based Spring JMS integration, auditing by using the Spring AOP configuration andSpring JMX integration.

2.2. A comparative look of the project modulesThe modules (Maven artifacts) of the project are outlined in the following table:

Table 2.1. Modules of the Sportsclub project

Maven Module Functionality Module Type

snowdrop-domain Domain classes and repositoryinterfaces.

jar

Sportsclub-hibernate-dao Hibernate implementations forrepositories and Spring beandefinitions using them.

jar

Sportsclub-jpa-dao JPA implementations forrepositories and Spring beandefinitions using them.

jar

Sportsclub-invoicing-ejb Business logic for the Invoicingapplication

ejb

Sportsclub-reservations-spring Business logic for theReservations application

jar

Sportsclub-subscriptions-ejb Business logic for theSubscriptions application

ejb

Sportsclub-invoicing-webmvc UI layer for the Invoicingapplication. Includesprocessing of JMS messagesvia Spring (for paymentnotifications)

war

Sportsclub-reservations-web UI layer for the Reservationsapplication.

war

Sportsclub-subscriptions-web UI layer for the Subscriptionsapplication

war

Sportsclub-ear EAR aggregator moduleusing the Hibernate-basedimplementation

ear

Sportsclub-jpa-ear EAR aggregator module usingthe JPA-based implementation

ear

Sportsclub-staticwebcontent Static web content for theapplication (not deployedseparately, but included atbuild-time in the web layers)

war

Sportsclub-test-infrastructure Infrastructure module for unittesting

jar

Page 15: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3.

7

Using JBoss and Spring togetherThis chapter will describe the various Spring and JBoss integration use cases covered by theapplication and how are they implemented in the various application modules.

As a Spring application that consists of multiple modules, the main strategy of constructing the globalSpring configuration is to provide Spring bean definition fragments in each artifact produced by amodule, leaving to the upper layer components to aggregate them by importing. This strategy hasmultiple benefits: for one, it allows the separation of concerns between components - the Spring wiringof certain components is left at the level where the components are defined, so that it can be changedeasily if the implementations change.

3.1. A look at the JBoss/Spring integration use casesThe Sportsclub application covers a number of JBoss and Spring integration use cases. The scenariosselected for this example are focusing on using the Java EE 5 services provided by JBoss EnterprisePlatforms in Spring applications.

The use cases can be grouped in categories as follows:

Table 3.1. Use case list overview

Category Use case How does this involveJBoss Enterprise Platforms

Persistence Spring/Hibernate integration The application is using aSpring-configured HibernateSessionFactory using JTAtransaction management andbound to JTA. The Hibernatelibrary being used is the oneprovided by JBoss EnterprisePlatforms.

Spring/JPA integration The Persistence Unit isdeployed by your JBossEnterprise Platform andretrieved from JNDI to beinjected into Spring beans.PersistenceContext is sharedwith surrounding EJBs (if any)

Testing Unit-testing components thathave managed infrastructuredependencies

The DataSource andEntityManager are managed byJBoss and acquired from JNDIby Spring when the applicationis running. In the case ofJBoss Enterprise Platforms,developers can test theircode in isolation using Spring-specific replacements that'simulate' the JBoss EnterprisePlatform environment.

Business Logic Spring-based service beans The business services areSpring-managed and wrappedinto transactions managedby Spring's interceptors. The

Page 16: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

8

Category Use case How does this involveJBoss Enterprise Platforms

TransactionManager in use isthe JTATransactionManagerusing JBoss Transactionsprovided in JBoss EnterprisePlatforms.

EJBs injected with SpringBeans

The application uses JBoss-deployed EJBs which areinjected with Spring beansacquired from an applicationcontext bootstrapped by theSpring Deployer. Transactionsare managed by EJBs.

User Interface JSF/RichFaces and Springintegration

The application uses the JBossEnterprise Platforms-providedJSF support, and RichFacescomponents. The businessservices and UI-backinginstances are Spring beans.

Spring MVC and EJBintegration

The application uses SpringMVC and the business logicis implemented using JBoss-deployed EJBs, which areinjected into the Springcontrollers.

JMS/JCA integration JMS/Spring integration usingJCA

Spring-configured messagelisteners are used forprocessing JMS messagesfrom JBoss EnterprisePlatforms-manageddestinations. The applicationuses the Spring /JCAintegration for receivingmessages.

Aspect-oriented programming Spring-based weaving of POJOaspects

This use case does nothave any JBoss EnterprisePlatforms-specific functionality.

JMX Spring beans are exposed asJMX beans

The JBoss Enterprise PlatformsMBean Server is used forregistering the Spring-exportedJMX beans. Consequently, theSpring beans can be managedfrom the JBoss EnterprisePlatforms AdministrationConsole.

Web Services JAX-WS defined web-servicesare injected with Spring beans

The application uses JBossEnterprise Platforms' supportfor JAX-WS through JBossWS, but also Spring to definethe underlying business logic,

Page 17: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

The domain model

9

Category Use case How does this involveJBoss Enterprise Platforms

which is injected into the JBossWS-deployed services.

3.2. The domain modelThe Sportsclub-domain module is the only module of the application that does not integrate withSpring directly. However, it is used further in the application as it provides:

• the entities that the application will interact with;

• the repository interfaces that provide persistence services for the application;

A relevant note regarding the domain module is the use of the term "repository" for the componentsthat are used for retrieving objects from persistence and saving them. The intent behind that is toindicate that the design of the application is emulating the concepts behind Domain-Driven Design,where the objects that are used for providing the persistence and entity lookup functions are part ofthe domain, rather than simple persistence implementation strategies (as it is the case with the fairlysimilar Data Access Objects).

Figure 3.1. Domain entities of the application and their connections

Figure 3.1, “Domain entities of the application and their connections” shows the domain entities of theapplication. A few non-entity domain objects have been ommitted from the diagram. Figure 3.2, “TheAccount and Person entities” shows a more detailed overview of the entities involved in the Account/Person relationship, including the non-entity domain objects.

Page 18: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

10

Figure 3.2. The Account and Person entities

3.3. Persistence implementation: JPA and HibernateThe persistence modules: Sportsclub-hibernate-dao and Sportsclub-jpa-dao are alternativeimplementations of the application's persistence strategy. This means that each module will provide:

• implementations for the repository interfaces defined in the Sportsclub-domain module;

• Spring context definition fragments that can be reused elsewhere in the application

Effectively, the Spring configuration fragments will expose a bean implementation for each repositoryinterface defined in the model. This means that the implementations can be swapped at build-time without any change in the business layer. This is the basis for the build process creating twodifferent builds, each based on a different persistence implementation - including a different repositoryimplementation jar and leaving everyting else in the component stack unchanged.

Each module produces a set of beans that can be injected further into the business services of theapplication.

3.3.1. The Hibernate implementationThe Hibernate-based repository implementation defines a generic superclass defining all the commonrepository operations that that repository implementations will parametrize by specifying the entity typeand primary key type.

public abstract class HibernateRepository<T, I extends Serializable> implements Repository<T, I>{ protected SessionFactory sessionFactory;

Class<T> clazz;

public HibernateRepository(Class<T> clazz) { this.clazz = clazz; }

public void setSessionFactory(SessionFactory sessionFactory) {

Page 19: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

The JPA implementation

11

this.sessionFactory = sessionFactory; }

protected Session getCurrentSession() { return this.sessionFactory.getCurrentSession(); } public T findById(I id) { return (T)getCurrentSession().get(clazz, id); }

public void save(T object) { getCurrentSession().saveOrUpdate(object); }

public void delete(T object) { getCurrentSession().delete(object); }

public List<T> findAll() { return getCurrentSession().createCriteria(clazz).list(); }

public long countAll() { return (Integer)getCurrentSession().createCriteria(clazz).setProjection(Projections.count("id")).uniqueResult(); }

public Criteria applyRange(Criteria criteria, Range range) { return criteria.setFirstResult(range.getMinIndex()).setMaxResults(range.length()); }}

It is important to notice that this implementation and its subclasses are not Spring-based.

The only Spring-related component of this module is the configuration which consists of two files:

spring-hibernate-dao/src/main/resources/dao-context.xmlContains the Spring bean definitions for the repository implementations, the Spring-basedSessionFactory definition (a LocalSessionFactoryBean) and the wiring of sessionfactories into Spring beans.

spring-hibernate-dao/src/main/resources/infrastructure.xmlContains the definitions for infrastructure-related Spring beans, namely the data source to be usedfor the Hibernate SessionFactory and the transaction manager.

Separating the infrastructure context definition file from the rest of the bean definitions allows to swapthe infrastructure definition for unit testing. For example, the Hibernate SessionFactory is configured touse JTA transactions, and allows the Session to shared with a layer of EJBs that delegate to it.

3.3.2. The JPA implementationThe JPA implementation is, in many respects, very similar to the Hibernate implementation (thereforewe won't provide a code example for it). It provides a parametrized superclass that is Spring-agnosticas well (except for the usage of the autowiring annotation - which can be replaced by a simple setter

Page 20: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

12

if any reference to Spring needs to be removed). Besides the fact that it is using the JPA API - forexample an EntityManager instead of the SessionFactory, the JPA Persistence Unit (and subsequentEntityManager) are created by the application server and not created by Spring (the EntityManageris injected by Spring, but acquired from JNDI). The persistence unit is deployed from within theJPA repository jar, in order to allow the spring-domain jar to be deployed in non-JPA scenarios (e.g.Hibernate) without triggering a persistence unit deployment.

The Spring application context configuration fragments are very similar to the ones encountered in theHibernate module:

spring-jpa-dao/src/main/resources/dao-context.xmlContains the Spring bean definitions for the repository implementations, assuming anEntityManager bean is defined in the global application context definition.

spring-jpa-dao/src/main/resources/infrastructure.xmlContains the definitions for infrastructure-related Spring beans, namely the data source to be usedfor the Hibernate SessionFactory and the transaction manager.

3.3.3. Unit testing the repositoriesWith the infrastructure so tied to the Application Server, how can we test the repositories in isolation,making sure that they work properly, before we even consider integrating them with the rest of theapplication?

If at deployment time we will use the JBoss Application Server provided services, for testing weare going to use an embedded database, and Spring's ability to create LocalSessionFactories,LocalEntityManagerFactories and its local transaction management abilities.

For this, we are going to use the spring-test-infrastructure module, which is a test-scopeddependency. This module contains the modules used for setting up an embedded database(producing a DataSource that can be injected into the LocalSessionFactoryBean andLocalContainerEntityManagerFactoryBean, respectively). The localized SessionFactory andEntityManager definitions are located in the spring-hibernate-dao and spring-jpa-dao modules,respectively.

The unit tests that are located in the respective modules will use the local infrastructure files and thedao-context.xml files, as in the following example:

@ContextConfiguration(locations = {"classpath:test-db-infrastructure.xml", "classpath:TEST-jpa-infrastructure.xml", "classpath:dao-context.xml"})@RunWith(SpringJUnit4ClassRunner.class)public class TestJpaAccountRepository{ /* */}

This configuration reuses the 'application-specific' context configuration fragment, as well as two test-specific (or otherwise said local) context configuration fragments in order to create a Spring contextin isolation. Thus, the functionality provided by the repositories can be tested outside the runningapplication.

3.4. Service LayerOn top of the domain and persistence layer sits the service layer of the application. Its role is toco-ordinate the domain objects and repositories in order to perform higher level operations. This

Page 21: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

The Spring-based service layer

13

is also the layer which provides transaction demarcation. One consideration for which transactiondemarcation should be done at service level is to ensure that the changes made by service operationsare atomic. Otherwise, concurrent operations may leave the application data in an inconsistentstate. Demarcating transactions at the repository/DAO level should be done carefully, taking intoconsideration that multiple repository/DAO invocations that are not surrounded by a wrappingtransactions will execute in separate transactional contexts.

In the Sportsclub application, there are two variants of implementing the service layer:

• using Spring (Reservations, parts of Invoicing)

• using EJB (Subscriptions, Invoicing)

Note

It is possible to define transactions at the repository level, thus avoiding another indirection to thepersistence layer for simple persistence operations (finding an object, persisting an object).

3.4.1. The Spring-based service layerThe Spring-based service layer exposes a number of service beans that can be consumed by theUI, which are injected with the beans defined in the persistence layer. Given how this is a fairlystraightforward Spring configuration, we will non insist any more on this topic, except for outliningthat this is the level where transaction demarcation is provided by the use of the appropriate Springannotations.

3.4.2. The EJB service layerA common scenario in Spring/EJB integration is the wrapping of Spring Beans in EJBs. This isvery often done in order to get advantage of the services provided by the EJB container (security,declarative transaction management), while keeping some of the objects they collaborate with assimple POJOs. In this scenario, the EJBs form the outermost layer of the business logic, the one thatis exposed to the rest of the application (UI). In this scenario, the EJB services are injected with theSpring-based repositories.

JBoss has its own native support for Spring/EJB integration, in the form of the Spring Deployer andspecial annotations for injection of Spring beans into EJBs.

3.4.2.1. The Spring DeployerThe Spring Deployer is a JBoss-specific deployer that can be used to bootstrap a SpringApplicationContext and register it into JNDI. The configuration files for bootstrapping the applicationcontext are defined at the EAR level, and the Spring ApplicationContext is shared to all thecomponents. The definition file is simple, and just imports the contexts defined in the JPA jars.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<description>BeanFactory=(SpringDao)</description>

<import resource="classpath*:dao-context.xml"/> <import resource="classpath*:infrastructure.xml"/>

Page 22: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

14

</beans>

3.4.2.2. Injection into EJBsOnce the ApplicationContext is created, the beans defined there can be injected into EJBs. So, in thiscase, the Spring repositories will be injected into EJBs as follows:

@Stateless@Interceptors(SpringLifecycleInterceptor.class)@LocalBinding(jndiBinding="Sportsclub/BillingService")public class BillingServiceImpl implements BillingService{ @Spring(bean = "invoiceRepository", jndiName = "SpringDao") private InvoiceRepository invoiceRepository;

/* rest of the class definition ommitted */}

The injection task is undertaken by the SpringLifecycleInterceptor. Once it encounters a field orsetter annotated with @Spring, it will look for the JNDI-bound application context and inject thecorresponding Spring bean.

3.5. Presentation LayerThe three web applications which compose the Sportsclub package illustrate different ways ofintegrating Spring and Java EE technologies in the presentation layer:

• JSF/EJB with an underlying Spring layer (Subscriptions)

• JSF/Spring (Reservations)

• Spring MVC/EJB (Invoicing)

3.5.1. Subscriptions: JSF and SpringThe Subscriptions application uses RichFaces and JSF for the presentation layer and EJB for thebusiness layer, so this part of the application is not Spring-related.

Although this is somewhat out of the Spring topic, it is worth mentioning for the benefit of the readerthat we recommend using Seam for building applications that integrate JSF and EJB in Java EE 5.This type of integration is, however, beyond the scope of the current demo application, so this exampleis not demonstrating it. Please consult the Seam documentation for detai.

3.5.2. Reservations: JSF/Spring integrationThe Reservations application is an example of using Spring in an application that uses RichFaces andJSF. Here, Spring beans are used as business services for the application, as well as backing beansfor the JSF pages. In the latter case, Spring beans replace the managed beans and other web artifactsused by JSF.

The Spring application context is bootstrapped by the ContextLoaderListener defined in /WEB-INF/web.xml. The Spring configuration file in use is /WEB-INF/spring-beans.xml, which:

• imports the context definition fragments included in the other JARs of the application (i.e. the JARsthat contain the business logic, defined at 4.1)

Page 23: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Reservations: JSF/Spring integration

15

• defines a number of Spring beans that are used directly in the web tier by the JSF pages or by theRichFaces components;

The Spring configuration file imports the Spring business beans and infrastructure definitions asfollows:

<import resource="classpath*:reservations-service.xml"/>

<import resource="classpath*:infrastructure.xml"/>

The following bean is used for backing JSF pages. Please note that Spring beans defined in the weblayer may use scopes, and a significant number of the Spring beans used in Reservations applicationare session-scoped (like the one in the following example). Spring provides a request scope as well,but it is not used in this example.

<bean id="reservationCreate" class="org.jboss.snowdrop.samples.Sportsclub.jsf.beans.ReservationCreate" scope="session" init-method="init"> <property name="reservationService" ref="reservationService"/> <property name="accountService" ref="accountService"/> <property name="accountFilter" ref="accountFilterCreate"/> <property name="equipmentFilter" ref="equipmentFilterCreate"/></bean>

In order to make the Spring beans visible to JSF pages, a special VariableResolver has to be definedin /WEB-INF/faces-config.xml.

<application> <!-- other definitions --> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver></application>

Now, we can use the Spring bean defined above directly in a JSF page, as in the following excerptfrom createReservation.xhtml:

<rich:panel> <f:facet name="header">Select Account</f:facet> <h:form id="AccountSelectForm"> <rich:extendedDataTable id="accountsTable" value="#{accountFilterCreate}" var="account" selectionMode="single" selection="#{accountFilterCreate.selection}" enableContextMenu="true" height="250px" rows="5"> <a4j:support event="onselectionchange" action="#{reservationCreate.updateSelectedAccount}" reRender="reservationDetails"/>

<rich:column label="Id" width="7%"> <f:facet name="header"> <h:outputText value="Id"/> </f:facet> <h:outputText value="#{account.id}"/> </rich:column>

<rich:column label="First Name"> <f:facet name="header"> <h:outputText value="First Name"/> </f:facet> <h:outputText value="#{account.subscriber.name.firstName}"/> </rich:column>

Page 24: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

16

<rich:column label="Last Name"> <f:facet name="header"> <h:outputText value="Last Name"/> </f:facet> <h:outputText value="#{account.subscriber.name.lastName}"/> </rich:column>

<rich:column label="City"> <f:facet name="header"> <h:outputText value="City"/> </f:facet> <h:outputText value="#{account.subscriber.address.city}"/> </rich:column>

<rich:column label="Country"> <f:facet name="header"> <h:outputText value="Country"/> </f:facet> <h:outputText value="#{account.subscriber.address.country}"/> </rich:column>

<f:facet name="footer"> <rich:datascroller id="scrollerAccount" for="accountsTable" maxPages="5" page="#{accountFilterCreate.currentPage}"/> </f:facet> </rich:extendedDataTable> </h:form></rich:panel>

All the EL variables that are used in the previous example, including the ones referenced in theRichFaces elements are, in fact, Spring beans. They can be used either as backing beans forretrieving and setting values, as well as for invoking methods corresponding to JSF events.

3.5.3. Invoicing: Spring MVC and EJBThe Invoicing application provides another example of interoperability between Spring and the JavaEE services provided by JBoss. If in the previous example, the business tier was implemented usingSpring and the web tier was using JSF, in this example the roles are reversed: the business tier isusing EJB and the web tier is using Spring.

The Spring MVC beans are defined in the /WEB-INF/spring-servlet-context.xml file, referenced by theSpring MVC DispatcherServlet definition that is described WEB-INF/web.xml. For this implementation,we have chosen the Spring 2.5 annotation-based configuration, and the AccountController class thatimplements the controller part of the configuration is injected with EJBs defined in section 3.2:

@Controllerpublic class AccountController{

@EJB(mappedName = "Sportsclub/BillingService") BillingService billingService;

@EJB(mappedName = "Sportsclub/SubscriptionService") SubscriptionService subscriptionService;

/* some code ommitted */

@RequestMapping(value = "/accountDetail.do", method = RequestMethod.GET) ModelMap getAccountDetail(@RequestParam("id") String id) { Account account = subscriptionService.findAccountById(Long.parseLong(id));

Page 25: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Invoicing: Spring MVC and EJB

17

List<Invoice> invoices = billingService.getInvoices(account);

boolean hasCurrentInvoice = false; Date currentDate = new Date();

for (Invoice invoice: invoices) { if (invoice.getBillingPeriod().contains(currentDate)) { hasCurrentInvoice = true; break; } }

List<Payment> payments = billingService.getPayments(account);

ModelMap model = new ModelMap(); model.addAttribute(account); model.addAttribute("invoices", invoices); model.addAttribute("payments", payments); model.addAttribute("hasCurrentInvoice",hasCurrentInvoice); return model; }

@RequestMapping(value = "/generateInvoice.do", method = RequestMethod.POST) ModelMap generateInvoice(@RequestParam("id") String id) { Account account = subscriptionService.findAccountById(Long.parseLong(id)); Invoice invoice = billingService.generateInvoice(account);

ModelMap model = new ModelMap(); model.addAttribute("id",id); model.addAttribute(invoice); return model; }

}

The @Controller annotation will be detected by Spring, as it does a scanning of the classpath which isprompted by including the following line into /WEB-INF/spring-servlet-context.xml.

<context:component-scan base-package="org.jboss.snowdrop.samples.Sportsclub.springmvc"/>

As a Spring-managed object, the bean is injected with the EJBs BillingService andSubscriptionService, as required by annotated the respective fields with the @EJB annotation.

The @RequestMapping-annotated methods will be executed when the user is accessing the specifiedURL and HTTP method. The request parameters will be bound to method arguments. In the exampleabove, invoking the URL http://localhost:8080/sportsclub/invoicing/accountDetail.do?id=1 will causethe invocation accountController.getAccountDetail(1). The method will invoke the appropriate businessservices (in this case, exposed as EJBs) and will return a map of business object collections, indexedby their names. Spring MVC will take care of setting them on the request, so that they can be used forrendering the response.

By default, Spring MVC will try to find a view whose name is 'accountDetail', and based on the viewresolver definition from /WEB-INF/spring-servlet-context.xml, it will use the JSP file at /WEB-INF/jsp/accountDetail.jsp. This JSP uses the Spring tag libraries for form processing, so that the collectionspreviously returned will be accessible using JSTL expressions, and furthermore, we will find thefollowing declaration:

<form:form action="generateInvoice.do">

Page 26: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

18

This account does not have an invoice for the current billing period.<p/> You can create one now: <input type="hidden" name="id" value="<c:out value="${account.id}"/>"> <input type="submit" value="Create invoice"/><br/> </form:form>

Clicking the 'Create Invoice' button will result in a POST submission to http://localhost:8080/sportsclub/invoicing/generateInvoice.do?id=1 and the subsequent invocation of the generateInvoice method.

A small note here: in order to be able to demonstrate a few Spring/JBoss integration features, theInvoicing application also contains a number of business services that are using Spring. They do notplay any role in the Spring MVC/EJB integration, and we will discuss more about them in section 6.

3.5.4. A problem of reusing contentHaving three different web applications to be included in the same package raises the problem ofreusing some content. Surely, the images and stylesheets that are part of the application design canbe copied in each individual project, but this raises the problem of maintainability. Therefore, most ofthe static content used by the Sportsclub application is defined in a separate web module, Sportsclub-staticwebcontent, which is then included by Maven at build time as follows:

<dependency> <groupId>org.jboss.snowdrop.samples.sportsclub</groupId> <artifactId>sportsclub-staticwebcontent</artifactId> <version>${project.version}</version> <type>war</type> <scope>runtime</scope></dependency>

Note

When working in an IDE this might produce an undesirable side-effect. If the IDE does notknow how to apply Maven overlays correctly, the static content may not be available whenbuilding and deploying the application through the IDE, without Maven. This does not affect thegeneral functionality of the application but may affect the look and feel in that particular situation.However, if the application is build using Maven, this will not be a problem.

3.6. Enterprise Integration FeaturesApart from the Spring/JSF/EJB integration, which you have seen in the previous sections, theSportsclub application suite provides a few other examples of integrating Spring and JBoss. Sinceall the features are Spring-based, they have been included as business services of the Invoicingweb application. All the definitions for the following examples can be found in the /WEB-INF/spring-business-context.xml file defined in the spring-invoicing-webmvc module.

3.6.1. Payment processing: JMS integration through JCAJMS integration can be enabled or disabled in the application, in order to allow it to run inenvironments that dot have a message broker, like for example the Web Profile of JBoss ApplicationServer. For details on how to do that, please consult section 1.1 of the current guide.

Besides displaying the current status of invoices and payments for a given account and generatinginvoices through the web interface, the Sportsclub application can also process payments for variousaccounts. The assumption of this scenario is that the system can receive payment notifications

Page 27: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Payment processing: JMS integration through JCA

19

asynchronously, through a JMS queue. Once such a payment has been received, it can be processedby a message-driven component, which in our case is a Spring bean. In order to take full advantage ofthe managed environment provided by the application server, the Spring bean will be invoked in a JCAcontext.

The component that processes JMS messages is a POJO:

public class PaymentNotificationProcessor{ private static final Log LOG = LogFactory.getLog(PaymentNotificationProcessor.class);

@Autowired private PaymentProcessor paymentProcessor;

public void processPaymentNotification(PaymentNotification paymentNotification) { LOG.info(paymentNotification + " received"); paymentProcessor.processPayment(paymentNotification.getAccountNumber(), paymentNotification.getAmount()); LOG.info(paymentNotification + " processed"); }

}

It delegates the actual processing of a PaymentNotification to a different component, thePaymentProcessor, which is injected in the PaymentNotificationProcessor. This is done in order tomaintain a degree of separation between the way data may be represented when exchanged overthe messaging system (i.e. encapsulated in a PaymentNotification object), and the contract of theinternal component which actually does the processing. The PaymentProcessor instance injected intothe PaymentNotificationProcessor is, in fact, reused by the PaymentNotificationService web serviceimplementation (whose contract does not depend on the PaymentNotification entity).

The arrival of messages and their processing can be traced by examining the application log.

Spring will instantiate a bean named "paymentNotificationProcessor" which will be registered as aprocessor for JMS message as follows:

<jms:jca-listener-container resource-adapter="resourceAdapter" acknowledge="auto" activation-spec-factory="activationSpecFactory"> <jms:listener destination="/queue/Sportsclub" ref="paymentNotificationProcessor" method="processPaymentNotification"/></jms:jca-listener-container>

This type of configuration uses the JCA infrastructure to deliver messages to the listener, as opposedto the DefaultMessageListenerContainer which is effectively polling the destination for incomingmessages. Using JCA will ensure better performance, as well as the ability to integrate with the JTAtransaction manager out of the box.

In order to be able to test this feature, messages have to be sent to the message queue. This canbe done by using a special MBean defined by the application, accessible from the JBoss EnterprisePlatforms JMX console. The name of the bean is "Sportsclub:name=paymentNotificationTrigger" andhas an operation called 'sendPaymentNotification' with two arguments:

• a long value, which is the accountId for making the payment;

• a double value, which represents the amount to be paid;

Once the JMX operation is invoked, a message is sent to the queue and a confirmation message willbe displayed in the JBoss log.

Page 28: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

20

3.6.2. Aspects and auditingPayments must be audited. Besides keeping a record of payments associated with an account, wemay want to set up an auditing service that will audit every attempt of making a payment. In thesimplest case we can just log that information, although in a real life scenario things may be moresophisticated. In order to do so, we set up a PaymentAuditor aspect that intercepts every call made tothe PaymentProcessor.

The aspect is a simple POJO:

public class PaymentAuditor{ /* code ommitted */

public void auditPayment(Long accountId, BigDecimal amount) { System.out.println("AUDIT ENABLED! A payment has been made to account " + accountId + " for the amount of " + amount); }}

The aspect is applied through the following definitions:

<aop:config> <aop:aspect ref="paymentAuditor"> <aop:pointcut id="processingPayment" expression="execution(* *..PaymentProcessor+.*(..)) && args(accountId, amount)"/> <aop:before arg-names="accountId, amount" pointcut-ref="processingPayment" method="auditPayment"/> </aop:aspect></aop:config>

<bean id="paymentAuditor" class="org.jboss.snowdrop.samples.sportsclub.audit.PaymentAuditor"/>

As you can see, the aspect is defined as a bean and applied as an aspect through the Spring aopnamespace. The pointcut definition is an AspectJ expression.

3.6.3. Configuring Spring beans through JMXJMX is a very important tool for monitoring and configuring Java applications. Collecting informationabout the system and the ability of making configuration at runtime are important administrationfeatures. For this example, the requirement is to be able to turn auditing on and off, at runtime,whenever required. Removing an aspect once it has been applied by Spring is not possible, so thesolution in this case is to define a flag property on the aspect, which controls whether the auditingfunctionality will be invoked or not.

In order to be able to make changes at runtime, the Spring bean which implements the aspect will beconfigured as a JMX bean and registered in the MBean server of JBoss. In this example, we are usingannotations to define Spring-specific JMX metadata. The complete definition for the PaymentAuditoris:

@ManagedResource(objectName = "sportsclub:name=paymentAuditor", description = "Payment Auditor")@Componentpublic class PaymentAuditor{

Page 29: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Payment processing: exposing a JAX-WS web service

21

private static final Log LOG = LogFactory.getLog(PaymentAuditor.class);

private boolean enabled = true;

@ManagedAttribute(description = "Audit enabled") public void setEnabled(boolean enabled) { LOG.info("Audit " + (enabled ? "enabled":"disabled")); this.enabled = enabled; }

@ManagedAttribute(description = "Audit enabled") public boolean getEnabled() { return this.enabled; }

public void auditPayment(Long accountId, BigDecimal amount) { if (this.enabled) { LOG.info("A payment has been made to account " + accountId + " for the amount of " + amount); } }}

The annotations ManagedResource and ManagedAttribute are using to indicate what classes andproperties are JMX-managed. In order to expose the bean through JMX, it must be exported usingSpring's MBean Exporter.

<bean id="attributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>

<bean class="org.springframework.jmx.export.MBeanExporter"> <property name="autodetectModeName" value="AUTODETECT_ASSEMBLER"/> <property name="ensureUniqueRuntimeObjectNames" value="true"/> <property name="namingStrategy"> <bean class="org.springframework.jmx.export.naming.MetadataNamingStrategy"> <property name="attributeSource" ref="attributeSource"/> </bean> </property> <property name="assembler"> <bean class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler"> <property name="attributeSource" ref="attributeSource"/> </bean> </property> </bean>

As a result, you can turn this functionality on and off directly from the JBoss Enterprise PlatformsJMX administration console, using the "sportsclub:name=paymentAuditor" bean to interact with thepayment auditor.

As explained in the JMS section, a separate MBean is set up for setting messages to the paymentnotifications message queue.

3.6.4. Payment processing: exposing a JAX-WS web serviceAnother way of interacting with external applications, is by exposing a web service. In this scenario,payment notifications may not arrive only as asynchronous events on a message queue, but also assynchronous web service invocations. For this purpose, the application will expose a Spring bean withJAX-WS annotations as a web service.

Page 30: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

Chapter 3. Using JBoss and Spring together

22

To that end, a JAX-WS annotated class is provided by the application:

@WebServicepublic class PaymentNotificationService extends SpringBeanAutowiringSupport{

@Autowired private PaymentProcessor paymentProcessor;

@WebMethod public Long notifyPayment(Long accountNumber, BigDecimal amount) { return paymentProcessor.processPayment(accountNumber, amount); }

}

By extending SpringBeanAutowiringSupport, the class PaymentNotificationService will be injectedautomatically with the same PaymentProcessor instance that is used by the JMS notificationprocessor, and defined in the application context created from WEB-INF/spring-business-context.xml.This is necessary, because no bean of the type PaymentNotificationService is defined in theapplication context. Instead, the web service is defined and mapped as a servlet in /WEB-INF/web.xml:

<servlet> <servlet-name>PaymentNotificationService</servlet-name> <servlet-class>org.jboss.snowdrop.samples.sportsclub.ws.PaymentNotificationService</servlet-class> </servlet>

<servlet-mapping> <servlet-name>PaymentNotificationService</servlet-name> <url-pattern>/ws/payment</url-pattern> </servlet-mapping>

As a result, the a JAX-WS web service can be accessed at http://localhost:8080/ws/payment. Theservice can be tested using a free SOAP testing tool such as SOAP UI.

Page 31: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

23

Appendix A. Revision HistoryRevision 1.1-0 Wed May 19 2010 Laura Bailey [email protected]

Edited book for stylistic consistency.

Page 32: JBoss Web Framework Kit-1.1-Snowdrop Sports Club Example-En-US

24