The Spring Framework


On one hand, we dedicated two chapters to the Spring Framework, so you might be wondering why more Spring? The short and simple answer is that although technologies such as Hibernate are robust, they also have a single focus (object-relational mapping, for example). However, the Spring Framework is such a large framework and is loaded with so many features that it is difficult to cover everything about Spring even in a small book. So, let's look at some more examples of using Spring here.

Scheduling Jobs

It is not uncommon for many applications to have requirements for scheduled jobs to run, perhaps for batch processing, to send data to downstream applications or generate CPU-intensive reports at the end of the day. To facilitate the scheduling of jobs, many companies use schedulers such as Unix/Linux CRON, Computer Associate's Unicenter AutoSys, Microsoft's Scheduled Tasks feature, and so on.

Open Symphony's Quartz system (opensymphony.com) provides the capability to schedule jobs within Java programs, and the Spring Framework provides support for this product (and JDK timers). The Quartz API is much more robust than JDK timers because it provides powerful scheduling features such as CRON-like expressions (discussed next).

You might recall from Chapter 2, "The Sample Application: An Online Timesheet System," that the business requirements for our sample application, Time Expression, require a reminder email to be sent on Fridays at 2 p.m. Our two filesReminderEmail.java and timex-servlet.xmlcombined provide this functionality. ReminderEmail.java will be discussed in the next section. However, let's look at the code excerpt from timex-servlet.xml that schedules the job.

<!-- Spring job scheduling --> <bean        class=    "org.springframework.scheduling.quartz. MethodInvokingJobDetailFactoryBean">    <property name="targetObject" ref="reminderEmail" />    <property name="targetMethod" value="sendMail" /> </bean> <bean      >     <property name="jobDetail" ref="reminderEmailJobDetail" />h     <property name="cronExpression" value="0 0 14 ? * 6" /> </bean> <bean     >     <property name="triggers">         <list>             <ref bean="reminderEmailJobTrigger" />         </list>     </property> </bean>


Notice the 0 0 14 ? * 6 value; this is a CRON-like expression that indicates that the job should be run at 14:00 hours (or 2 p.m.) on Fridays (6 for the sixth day of the week). Also, visit quartz.sourceforge.net for detailed documentation on the Quartz API.

Another notable configuration item is how we tell Spring which target method in which target object to invoke for us, as shown next:

<property name="targetObject" ref="reminderEmail" /> <property name="targetMethod" value="sendMail" />


This feature requires Open Symphony's quartz.jar, available on the opensymphony.com website. In the case of Time Expression, we would need this to be installed in the timex/lib directory.

The one issue we face with running jobs inside a web or application server is if the server is clusteredthat is, there is more than one instance of the server. (Clustering is discussed later in the chapter.) As you might guess, the job will run on all instances (servers) in the clustered environment. To get around this problem, in the past, I have used a database technique to manage this job concurrency issue. This technique uses a table named ObjectLock with a column name isLocked. The isLocked column can be used to simulate a job lock; this can then be checked by the jobs to determine if the job is already running (that is, locked).

Spring Mail Support

As I mentioned earlier, our business requirements dictate that a reminder email be sent out to all employees who have not submitted a weekly timesheet. To implement this feature, we will use a simple mail-sending API provided by the Spring Framework, instead of using something like JavaMail directly. Note that Spring uses JavaMail for this mail support.

Our two files, ReminderEmail.java and timex-servlet.xml, combined provide this functionality. The following is the excerpt from the timex-servlet.xml file:

<bean      >     <property name="host" value="acme.com" />     <property name="username" value="myuserid" />     <property name="password" value="mypassword" /> </bean> <bean      >     <property name="from" value="me@me.com" />     <property name="subject" value="Reminder: Submit Timesheet" />     <property name="text"         value="Please don't forget to submit your timesheet. Thank you!" /> </bean> <bean      >     <property name="employeeManager">         <ref bean="employeeManager" />     </property>     <property name="mailSender">         <ref bean="mailSender" />     </property>     <property name="message">         <ref bean="reminderEmailMessage" />     </property> </bean>


The following method from ReminderEmail.java shows the actual code, which demonstrates how a list of emails is retrieved from the database (using one of our model classes from Chapter 5) for sending the email to various employees:

public void sendMail() {   List list = employeeManager.getHourlyEmployees();   if (list == null || list.size()< 1)     return;   String emailAddresses[] = new String[list.size()];   Employee employee;   for (int i=0; i < list.size(); i++)   {     employee = (Employee)list.get(i);     emailAddresses[i] = employee.getEmail();   }   message.setTo(emailAddresses);   SimpleMailMessage threadSafeMailMessage =     new SimpleMailMessage(message);   mailSender.send(threadSafeMailMessage); }


This feature requires mail.jar (part of the JavaMail API) and activation.jar (part of the JavaBeans Activation Framework) are present in the timex/lib directory. Both of these can be found on the java.sun.com website.

JMX Support

We looked at the Java Management Extensions (JMX) technology in the previous chapter. Although this technology is primarily used for managing servers currently, in my opinion it can easily be used to monitor business aspects of an application. For example, we could monitor how many users have logged on to the system for a given day, how many invoices were processed for an accounting system, how many claims were processed for an insurance system, and so on. This can be used not only to monitor the health of the application, but also to provide a comfort level that everything is operating in a business-as-usual fashion.

Spring's JMX support enables us to automatically register plain JavaBean objects. In our case, this is accomplished via two files: one is timex-servlet.xml and the other is a simple JavaBean class (TimexJmxBean.java) that tracks how many users signed into Time Expression and how many timesheets records were fetched.

The following is a code excerpt from timex-servlet.xml:

<bean       /> <bean      >     <property name="registrationBehaviorName"         value="REGISTRATION_IGNORE_EXISTING" />     <property name="beans">         <map>             <entry key="Time Expression:name=timex-stats"                 value-ref="timexJmxBean" />         </map>     </property> </bean>


The following code excerpt shows an excerpt from the TimexJmxBean.java:

public class TimexJmxBean {   private static int signInCount;   private static int timesheetsFetched;   public int getSignInCount()   {     return signInCount;


Figure 10.2 shows our JMX Bean in the JConsole application (bundled with JSE, 5.0). Again, this is a great way to monitor, right from your desktop, the health and status of applications running on a remote server! In my opinion, this provides a great view for developers versus larger and much more robust tools, such as HP's OpenView or Computer Associate's Unicenter related products, which are intended for use by operations departments.

Figure 10.2. JConsole with TimexJmxBean.


More Spring

Again, Spring is such a large framework and so loaded with features that I could cover only the ones applicable to our sample application.

New Tag Libraries

At the time of this writing, the most current version of the upcoming Spring Framework was M4 (or RC1). This version introduced several new tag libraries to ease working in JSP. Some of the new tags include form:form, form:input, form:password, form:hidden, form:select, form:option, form:radiobutton, form:checkbox, form:textarea, and form:errors.

The tag libraries mentioned here were still unstable and I was requested by the Spring Framework team to not cover these in detail until they became stable.

Visit the springframework.org website for the latest documentation and downloads.

Support for Web Services, JMS, JTA, EJB, DAO, RMI, JDBC

Spring also provides support for remoting protocols such as the Java Remote Method Invocation (RMI), Web Services (using JAX-RPC), Java Connector Architecture (JCA), DAO (Data Access Object) support for various object-relational mapping (ORM) products other than Hibernate (JDO and iBATIS, for example), and Java Database Connectivity (JDBC), EJB, Java Message Service (JMS), Java Transaction API (JTA), and more.

Startup Classes

You might be familiar with the concept of startup classes or servlets in web and application servers. Spring doesn't explicitly have the notion of startup classes. But this is easily done using the depends-on attribute for the bean element. Most of the objects are automatically created in the correct order because Spring resolves the dependencies.

However, if you have independent classes such as the HibernateUtil class, the depends-on attribute can come in handy for ensuring that those objects get instantiated beforehand, so they are prepared to be used by the objects that need them.

Other

Another notable feature is Spring's capability to load an external properties file, as shown in this example:

<bean        class= "org.springframework.beans.factory.config. PropertyPlaceholderConfigurer">   <property name="location" value="WEB-INF/classes/pas-servlet.properties"/> </bean>


After the properties file is loaded, it can be used to replace bean-related attribute values, as shown here:

<property name="url" value="${db.url}" />




Agile Java Development with Spring, Hibernate and Eclipse
Agile Java Development with Spring, Hibernate and Eclipse
ISBN: 0672328968
EAN: 2147483647
Year: 2006
Pages: 219

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net