Spring Book – Chapter 5 – Application Configuration – Simplified

Spring 3.0’s innovation SpEL

Although Chapter 19 focuses on Spring Expression Language (SpEL), I need to discuss this briefly in this chapter because this can be one of the ways you can simplify your XML configuration.

SpEL is powerful new expression language, introduced in Spring 3.0. This expression language is superset of unified expression language and inspired by WebFlow expression language. It can be used programmatically with XML or annotations.

SpEL can be used to access functions, call methods/constructors, access property and indexed collections etc. This expression language can be easily plugged and extended by all other Spring based frameworks/projects with ease. SpEL is created to help the Spring portfolio products. Another advantage of SpEL is that it can work independently without depending on the Spring environment as it can be used similar to other unified languages like OGNL etc.

SpEL is powerful and concise means of dynamically wiring values in constructor arguments or bean properties that are evaluated at runtime. With SpEL, it is now possible to have much more flexible bean wiring than it is possible to get using Spring’s traditional wiring style. SpEL has a great deal of functionality, including the following:

  • The ability to reference beans by their “id”
  • Invoking methods and accessing properties on objects
  • Mathematical, relational, and logical operations on values
  • Regular expression matching
  • Collection manipulation

There are two variables that you have at your disposable, namely “systemProperties” and “systemEnvironment”. SpEL allows us to access information from our beans and system beans information at runtime. SpEL uses a programming mechanism called late binding, in which the method being called on an object is looked up by name at runtime. (Informally, late binding is also known as duck typing or name binding.) SpEL can be applied to bean fields as defaults using the JSR-303 @Value annotation on a field or in XML with the <bean … value=”” /> options.

  • systemProperties – a java.util.Properties object retrieving properties from the runtime environment
  • systemEnvironment – a java.util.Properties object retrieving environment specific properties from the runtime environment

We can access specific elements from the properties and environment objects with the following syntax in Listing 5-42.

Listing 5-42. Usage of systemProperties and systemEnvironment in your application

[xml]#{systemProperties[‘property.name’]}

#{systemEnvironment[‘property.name’]}[/xml]

Listing 5-43. Usage of systemProperties in XML configuration

[xml]<bean id="loyaltyService" class="com.mybook.loyalty.services.LoyaltyServiceImpl">

<property name="locale" value="#{systemProperties[‘LOCALE’]}"/>

</bean>[/xml]

If you prefer annotation over XML, the Listing 5-44 gives an example of using SpEL in your annotations.

Listing 5-44. Usage of systemEnvironment in annotations

[java]@Service

public class LoyaltyServiceImpl{

@Value("#{systemEnvironment[‘LOCALE’]}")

String locale;

}[/java]

Other frameworks like Spring security also uses SpEL to aid the developers to do many things easy to do using this new Spring expression language.

Listing 5-45. Usage of SpEL in Spring security annotations

[java]@PreAuthorize("(hasRole(‘ROLE_GOLD_CUST’) and #weight

>= 1000.0) or hasRole(‘ROLE_PLATINUM_CUST’)")

public void allowCustomerToContinue(String customerCode, double weight) {

//… method implementation

}[/java]

Simply put, Listing 5-45 allows the customer to continue (allowCustomerToContinue method) if the customer is GOLD class and has a weight of cargo more than 1000 kilograms or if the customer is PLATINUM class.

Naming your Beans

Every bean has one or more ids, also called identifiers, or names. These ids must be unique within the Spring container in which the bean is hosted. A bean will usually have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases. When using XML configuration, you use the ‘id’ or ‘name’ attributes to specify the bean. The ‘id’ attribute allows you to specify exactly one id, and as it is a real XML element ID attribute.

Because it is an ID attribute, XML parser can perform some extra validation when other elements reference this id. However, the XML specification does limit the characters that are legal in XML IDs. If your bean identifier contains special character(s) for example (/myView.xhtml), it wont be allowed as the bean id, because it’s not a valid XML ID. In this case use ‘name’ instead of ‘id’ attribute. If you want to introduce other aliases to the bean, you may specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace. the id attribute conforms to the XML id attribute standards whereas name is a little more flexible.

Listing 5-46. Conventional way of defining a bean in XML configuration

[xml]<bean id="myBeanID"/>[/xml]

Listing 5-47. Using name attribute to define beans in XML configuration

[xml]<bean name="myBeanName"/>[/xml]

Listing 5-48. Using aliases to a bean using name attribute in XML configuration

[xml]<bean name="myBeanName1, myBeanName2, module/myBeanName"/>[/xml]

In Spring 3.1, XML ID restriction is removed so that you could use special characters for your bean id attribute as well.

Best Practice: Use the standard Java convention for instance field names when naming beans. That means bean names start with a lowercase letter, and are camel-cased from then on. Naming beans consistently makes your configuration easier to read and understand. Also if you plan to use Spring AOP extensively in your application, having consistent naming will enable you to easily put appropriate interceptors/hooks in your application.

Summary

As explained in Chapter 4, there are different ways by which to supply the metadata required by the Spring container to maintain your application namely XML, annotation and Java. But there are also different ways by which to simplify this configuration, of which we have covered few notables ones in this chapter.

If XML is preferred way of configuration in your application, there are different ways by which to simplify your application configuration like using bean inheritance, using inner beans etc. We covered these extensively using examples in this chapter. You should also move away from monolithic configuration in which the entire application has only one configuration file consisting of all the beans in the application. Using configuration import in a judicial way can solve this in an easy manner.

We also covered autowiring as a means of simplifying your bean XML configuration with various code snippets so that you can see these in real action.

As a way of simplifying your application configuration, we took a preliminary glance at Spring expression language (SpEL) and its usage with some example code snippets. We will be covering SpEL in detail in a separate chapter later on.

In addition we covered bean naming conventions and best practices which is very essential in an enterprise application.

After reading this chapter you should have learned different ways by which to simplify configuration in Spring framework. In the following chapter you’ll start implementing it in your application so that configuration is not cumbersome and so that you can promote reusability to the maximum extent in your application.

Page Visitors: 3753

The following two tabs change content below.
Tomcy John

Tomcy John

Blogger & Author at javacodebook
He is an Enterprise Java Specialist holding a degree in Engineering (B-Tech) with over 10 years of experience in several industries. He's currently working as Principal Architect at Emirates Group IT since 2005. Prior to this he has worked with Oracle Corporation and Ernst & Young. His main specialization is on various web technologies and acts as chief mentor and Architect to facilitate incorporating Spring as Corporate Standard in the organization.
Tomcy John

Latest posts by Tomcy John (see all)

2 thoughts on “Spring Book – Chapter 5 – Application Configuration – Simplified

  1. Hi Tomcy,

    All looks great and thanks for your time and efforts.

    One small suggestion if you could provide single page view for all the Spring tutorials would be great. May print option as well.

    Thanks & regards,
    AA

Leave a Reply

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