Spring Framework: Best Programming Practices Part 5

This is the fifth part of Spring Best Practices series as per Best practices introduction post. This fifth part is also related with the best practices when using Spring’s XML Configurations and its the continuation of Part 4. You can refer the other four posts through this links… Part 1, Part 2, Part 3 and Part 4. I am expecting the corrections (if any)as well as the new best ways from my readers

  • Use ids as bean identifiers

You can specify either an id or name as the bean identifier. Using ids will not increase readability, but it can leverage the XML parser to validate the bean references. If ids cannot be used due to XML IDREF constraints, you can use names as the bean identifiers. The issue with XML IDREF constraints is that the id must begin with a letter (or one of a few punctuation characters defined in the XML specification) followed by letters, digits, hyphens, underscores, colons, or full stops. In reality, it is very rare to run into the XML IDREF constraint problem.

  • Use dependency-check at the development phase

You can set the dependency-check attribute on a bean definition to a value other than the default none, such as simple, objects, or all, so that the container can do the dependency validation for you. It is useful when all of the properties (or certain categories of properties) of a bean must be set explicitly, or via autowiring.

   1: <bean id=”orderService” class=”com.spring.OrderService” dependency-check=”objects”>
   2:     <property name=”companyName” value=”valuemometum”/>
   3:     <constructor-arg ref=”orderDAO”/>
   4: </bean>

In this example, the container will ensure that properties that are not primitives or collections are set for the orderService bean. It is possible to enable the default dependency check for all of the beans, but this feature is rarely used because there can be beans with properties that don’t need to be set.

It is preferred to use descriptive ids and names instead of inline comments in the XML configuration files. In addition, it is helpful to add a configuration file header, which summarizes the beans defined in the file. Alternatively, you can add descriptions to the description element. For example

   1: <beans>
   2:     <description>This file defines billing servicerelated beans and 
   3:         it depends onbaseServices.xml,which providesservice bean templates…
   4:     </description>
   5: </beans>

One advantage of using the description element is that it is easy to for tools to pick up the description from this element.

  • Communicate with team members for changes

When you are refactoring Java source code, you need to make sure to update the configuration files accordingly and notify team members. The XML configurations are still code, and they are critical parts of the application, but they are hard to read and maintain. Most of the time, you need to read both the XML configurations and Java source code to figure out what is going on.

Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Typically we only use the first two types

In this example, the orderService bean uses constructor injection, while the BillingService bean uses setter injection. Constructor injection can ensure that a bean cannot be constructed in an invalid state, but setter injection is more flexible and manageable, especially when the class has multiple properties and some of them are optional.

  • Do not abuse dependency injection

As the last point, Spring ApplicationContext can create Java objects for you, but not all Java objects should be created through dependency injection. As an example, domain objects should not be created through ApplicationContext. Spring is an excellent framework, but, as far as the readability and manageability are concerned, the XML-based configuration can become an issue when many beans are defined. Overuse of dependency injection will make the XML configuration more complicated and bloated. Remember, with powerful IDEs, such as Eclipse and IntelliJ, Java code is much easier to read, maintain, and manage than XML files!

  • Comments to Configuration files as well as bean files

Add a description comment to each configuration file, which explains the reason for this file and summarizes the beans defined in it.For example

   1: <beans>
   2:     <description>This file defines billing service related beans and it depends 
   3:         on baseServices.xml,which provides service bean templates…
   4:     </description>…
   5: </beans>

Also we can place bean documentation in the description tag.For example

   1: <bean id=”aBean” class=”x.y.z.AClass”>
   2:     <description>Bean explanation</description>…
   3: </bean>

One advantage of using the description element is that it is easy for tools to pick up the description from this element.

  • Application Context Naming Conventions

Use the following naming convention for configuration filenames:applicationContext-<a describing name>.xml This makes the naming convention applications consistent.

  • Seperate deployment details from application context

Try to seperate deployment details out of application context in other xml or properties file.Example : You can specify datasource details in a property file using Spring’s PropertyPlaceHolderConfigurer or through JNDI.Property file:

   1: <bean id=”propertyConfigurer” class=”org.springframework.beans. factory.config.PropertyPlaceholderConfigurer”>
   2:     <property name=”location”>
   3:         <value>datasource.properties</value>
   4:     </property>
   5: </bean>
   6:  
   7: <bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
   8:     <property name=”url”>
   9:         <value>${database.url}</value>
  10:     </property>
  11:     <property name=”driverClassName”>
  12:         <value>${database.driver}</value>
  13:     </property>
  14:     <property name=”username“>
  15:         <value>${database.user}</value>
  16:     </property>
  17:     <property name=”password”>
  18:         <value>${database.password}</value>
  19:     </property>
  20: </bean>

datasource.properties should contain the following entries:

   1: database.url=jdbc:hsqldb:mydbdatabase.driver=org.hsqldb.jdbcDriverdatabase.user=hsqldatabase.password=passwordJndi :
   2: <bean id=”myDataSource” class=”org.springframework.jndi.JndiObjectFactoryBean”>
   3:     <property name=”jndiName” value=”jdbc/myDataSource” />
   4: </bean>

  • Use of Standard Naming convention.

Its better to use the standard Java convention for instance field names when naming beans (Hungarian Notation).

  • Use <null/> for null property

Use <null/> to initialize any property to null. Although simply leaving property without setting any value defaults to null but the property might be set to some other default value within bean or if you are using auto wiring.

Technorati Tags: , ,

Advertisements

Spring Framework: Best Programming Practices Part 2

 

This is the second part of Spring Best Practices series as per Best practices introduction post. This second part is also related with the best practices when using Spring’s Core classes and other utilities. You can refer the other four posts through this links… Part 1, Part 3, Part 4 and Part 5. I am expecting the corrections (if any)as well as the new best ways from my readers.

  • Configuring Spring Application context for different locations:

If the configuration is the same for all the environments except for the developer’s machine, then make (a) separate configuration file(s) with the configuration that is different. Let this different configuration overwrite the definition(s) in the original file(s).Make sure this different configuration will never be placed in the other environments!!!Example of how to achieve this if you use the org.springframework.context.support.ClassPathXmlApplicationContext:Note: I give every example file below a unique name, so I can easily refer to it.Contents of beanRefContext.xml

   1: <beans>
   2:     <bean id=”aBeanId”class=”org.springframework.context.support.ClassPathXmlApplicationContext”>
   3:         <constructor-arg>
   4:             <list>
   5:                 <value>
   6:                     /spring/applicationContext-forAllTheEnvironments.xml    
   7:                 </value>
   8:                 <value>
   9:                    /spring/applicationContext-local.xml
  10:                 </value>
  11:             </list>
  12:         </constructor-arg>
  13:         <constructor-arg>
  14:             <ref bean=”frameworkApplicationContextId”/>
  15:         </constructor-arg>
  16:     </bean>
  17: </beans>

Beans defined in the config locations (first constructor-arg) overwrite the beans in the parent application context (second constructor-arg).Quote from the JavaDoc of this class “In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.

  • Prefer static pointcut over dynamic point cut :

In Spring’s book of definitions static point cut refers to a pointcut that can be evaluated when a proxy is created. Criteria for static point cuts can not changed afterwards. Dynamic point cuts depend on runtime information such as arguement values or call stack.Dynamic pointcuts are slower to evaluate than static pointcuts and allow less potential for optimization. It’s always necessary to evaluate them on each invocation.

  • Use regular expression advisors to fine tune interceptor scope

Instead of using broad method point cuts and filtering target methods in interceptor, use more sophisticated and elegant regular expression at the application context level. Spring supports three types of regex method point cuts:· org.springframework.aop.support.JdkRegexpMethodPointcut : Java 1.4 regular expression for the fully-qualified method names to match.· org.springframework.aop.support.Perl5RegexpMethodPointcut : Perl5 regular expression for the fully-qualified method names to match· org.springframework.aop.support.RegexpMethodPointcutAdvisor : Convenient class for regexp method pointcuts that hold an Advice, making them an Advisor. By default, JdkRegexpMethodPointcut will be used on JDK 1.4+, falling back to Perl5RegexpMethodPointcut on JDK 1.3 (requiring Jakarta ORO on the classpath).Example:

   1: <bean id=”crudInterceptor” class=”com.mycompany.CrudInterceptor”/>
   2:  
   3: <bean id=”crud”class=”org.springframework.aop.support.RegexpMethodPointcutAdvisor”>
   4:     <property name=”advice”>
   5:         <ref local=” crudInterceptor “/>
   6:     </property>
   7:     <property name=”patterns”>
   8:         <value>
   9:             .*create.*,.*destroy.*,.*get.*,.*update.*
  10:         </value>
  11:     </property>
  12: </bean>

  • Use autoproxying for large applications

ProxyFactoryBean works well for small application but it requires more verbose configuration. It allows control over every aspect of the proxy. Spring ease the use of ProxyFactoryBean by providing dedicated proxies such as TransactionProxyFactoryBean and LocalStatelessSessionProxyFactoryBean. Proxies also saves code duplication in configurations.Example

   1: <bean id=”myProxy” class=”org.springframework.aop.framework.ProxyFactoryBean” abstract=”true”>
   2:     <property name=”interceptorNames”>
   3:         <list>
   4:             <value>interceptor1</value>
   5:             <value>interceptor2</value>
   6:         </list>
   7:     </property>
   8: </bean>
   9:  
  10: <bean id=”mybean” parent=”myProxy”>
  11:     <property name=”proxyInterfaces”>
  12:         <value>com.mycompany.mybean</value>
  13:     </property>
  14:     <property name=”target”>
  15:         <bean class=”com.mycompany.MyBeanImpl”>
  16:             <property name=”name”>
  17:                 <value>Dave</value>
  18:             </property>
  19:             <property name=”description”>
  20:                 <value>Good Boy</value>
  21:             </property>
  22:         </bean>
  23:     </property>
  24: </bean>

Here number of child bean definitions can “extend” the myProxy definition, specifying a target, usually inner bean. They can optionally add further properties, such as proxy interfaces. Autoproxying means that depending on some configuration, proxying is applied consistently to a number of objects. Autoproxy can be created using BeanNameAutoProxyCreator or DefaultAdvisorAutoProxyCreator. BeanNameAutoProxyCreator is good for replacing several ProxyFactoryBean. DefaultAdvisorAutoProxyCreator is powerful. It examines all advisors defined in current context for mathcing pointcut methods on target object. Both advisor and advices and be used in BeanNameAutoProxyCreator interceptor list. DefaultAdvisorAutoProxyCreator strictly requires Advisors.Examples:BeanNameAutoProxyCreator :

   1: <bean id=”bnProxyCreator” class=”org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator”>
   2:     <property name=”beanNames”>
   3:         <value>bean1,mybean*</value>
   4:     </property>
   5:     <property name=”interceptorNames”>
   6:         <list>
   7:             <value>advisor1</value>
   8:             <value>interceptor1</value>
   9:         </list>
  10:     </property>
  11: </bean>

DefaultAdvisorAutoProxyCreator :

   1: <bean id=”daaProxyCreator” class=”org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator”/ >

An autoproxy creator bean definition is intended to change the effect of other bean definitions, not for access by application code or other framework objects. Autoproxy can be used to define transactions as well. 15. Specify Transaction Rollback: By default transactions are rolled back only on runtime exceptions and not on checked exceptions. However it is a good practice to choose specific checked exceptions where you want the transaction to be rolled back based on business needs. Exceptions marked with negative (-) sign cause transaction to be rolled back.Example:

   1: <bean id=”businessBean” class=”org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource”>
   2:     <property>
   3:         <props>
   4:             <prop key=”businessMethod1″>
   5:                 PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ,-RollBackBusinessException
   6:             </prop>
   7:         </props>
   8:     </property>
   9: </bean>

You can even mark runtime exceptions as positive to prevent rollbacks but be careful while doing so as it could have adverse affects.

  • Aware of thread safe issues with AOP advice

Advice instances are most often shared among threads, so we need to consider thread safety issues. For example if the method interceptor is responsible for generating unique id or count, then consider using ThreadLocal variable with synchronized method for incrementing the count.Example:

   1: public class CountingMethodAdvice implements MethodInterceptor {
   2:  
   3:     // The next serial number to be assigned
   4:     private static long nextSerialNum = 0;
   5:  
   6:     private static ThreadLocal serialNum = new ThreadLocal() {
   7:         protected synchronized Object initialValue() {
   8:             return new Long(nextSerialNum++);
   9:         }
  10:     };
  11:     
  12:     private static long getCount() {
  13:         if(serialNum!=null){
  14:             return ((Long) (serialNum.get())).longValue();
  15:         }
  16:     }
  17:     public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  18:         System.out.println(”This method is called ” + getCount + ” times”);
  19:     }
  20: }

Technorati Tags: , ,