Spring Framework: Best Programming Practices Part 3

 

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

  • Prefer to use apache Connection pooling bean

In the spring DataSource Configuration we are commonly using class is “org.springframework.jdbc.datasource.DriverManagerDataSource”. We can implement connection pooling using the following class “org.apache.commons.dbcp.BasicDataSource”. For that we have to download its jar file from apache commons.Project site: http://commons.apache.org/dbcp/Download: http://commons.apache.org/downloads/download_dbcp.cgi

  • Handling Exceptions

Spring Gives a consistent exception hierarchy in its DAO level. All the SQL as well as DAO based exceptions are under the DataAccessException. With the effective handling of this exception, we can easily log the errors as well as we can more effectively assign “ERROR MESSAGES” to the error objects.We can also use Spring’s “org.springframework.web.servlet.handler.SimpleMappingExceptionResolver” class to get the exceptions thrown and can be displayed in the web level. This will help us to check the “Exceptions in a real distributed environment”.

  • Prefer to use Springs Declarative Transaction Capability

Spring provides Programmatic as well as Declarative Transaction capabilities. And if we are using any OR mapping tools then spring provides its own Transaction manager to handle it.

  • Transaction Attribute Settings.

Spring provides a distinct “ISOLATION behaviors” for handling transactions. In which the most efficient isolation level, but isolates the transaction the least, leaving the transaction open to dirty, no repeatable, and phantom reads. At the other extreme, ISOLATION_SERIALIZABLE prevents all forms of isolation problems but least efficient. So its better to choose according to our needs.

  • Better to perform unit testing in the DAO layer.

The Data Access Part is the important part in which errors are popping up. So if we complete a unit test here then it will be more useful for our service layer programming. It’s very easy to write unit tests in the spring DAO layers. Junit (http://www.junit.org/ ), easymock(http://www.easymock.org/ ), unitils (http://unitils.sourceforge.net/summary.html ) are some of the useful as well as mostly used Unit testing frameworks. Each one has its own advantages.

Technorati Tags: , ,

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: , ,

Spring Framework: Best Programming Practices Part 1

 

This is the first part of Spring Best Practices series as per my previous post. This post 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 2, Part 3, Part 4 and Part 5. I am expecting the corrections (if any)as well as the new best ways from my readers.

  • Using Spring’s “Bean Container” nature and Dependency Injection.

It’s better to create the Spring beans with dependencies at the start up with its lazy initialization is set as true. Whenever a class needed a bean we can use the setter injection or constructor injection to give an instance. This will lead the Spring to act as a real container of Beans and gives (in the case of Singleton) or creates bean instances (in the case of prototype) at the time of requirement. Spring is maintaining as its beans as “Singleton” default.

  • Prefer ApplicationContext over BeanFactory

BeanFactory is a simple factory implementation to create and destroy spring beans. ApplicationContext is an advanced beanfactory which supports i18N text message resolution, resource loading and capable to posting events to listener beans. BeanFactory should be preferred when there is limitation on resources and size of the application. Singleton beans are loaded differently in BeanFactory and ApplicationContext. A bean factory lazily loads all beans, deferring bean creation until the getBean() method is called. An application context loads all singleton beans upon context startup. Your application won’t have to wait for them to be created if you are using ApplicationContext.

  • Prefer setter-based dependency injection over constructor-based dependency

The Spring team generally advocates the usage of setter injection, since a large number of constructor arguments can get unwieldy, especially when some properties are optional. The setter injection is used in the following occasions.

  1. To prevent long argument lists for constructors.
  2. To prevent argument lists for constructors with arguments of the same type.
  3. To be able to use reflection. (In a compiled class file, constructor argument names are not retained. But setter and getter names are visible for reflection.)

Constructor-injection is favored by some purists though Supplying all of an object’s dependencies means that that object is never returned to client code in a less than totally initialized state. Constructor injection is also used to set required properties that don’t have default values.Constructor injectionSetter injectionStrong dependency contract. Bean cannot be instantiated without being given all ofits dependencies. Ready to use if all argument constructors are used. Good for bean with one or two properties.Suitable for beans with several properties which makes constructor injection very lengthy.Less code lines as setters could be avoided.Provides flexibility to create a valid object.Facilitates immutable property.Setters are self explaining. Constructor argument with same type might not be clear.

  • Singleton beans and Prototype beans

By default all beans defined in spring are singleton. However you can ask spring to create unique instance of a particular bean setting “singleton” property of the bean to false. Such beans are called prototype. A new instance of a prototype bean will be created each time getBean() is invoked with the bean’s name. Prototype beans incur hit on performance during creation. It should be avoided completely or designed carefully if it uses resources such as database or network connections. They are useful for factory to create new bean instances.

  • Inner beans

Use Inner beans when you don’t want a particular bean to available without its parent bean. Although it doesn’t look pleasing to most eyes, it is still worth if you don’t want beanfactory to use this bean. Example: target for AOP proxy.

  • Use “depends” if that depends on any other bean

If any bean is depended on other bean like any static variable is using or something then we must specify that bean inside the bean definition using the keyword “depends”. This helps Spring to initialize that bean before the initialization of the actual bean.

  • Aspect Oriented Programming in the necessary situations.

Use the ability of Aspect Oriented Programming in the necessary times.

  • Spring AOP and AspectJ AOP:

Spring provides proxy based aop implementation based on interceptor chains. It is also called dynamic AOP as changes in point cuts or joins doesn’t require recompilation. AspectJ works at byte code level and doesn’t require any framework once byte code is decorated with AOP capabilities. Here are some pros and cons of spring AOP which will help you to decide, which one to use:Pros:

  1. Spring AOP doesn’t require any special java compiler or special build process. AspectJ requires special compiler.
  2. Different advice could be applied to different instance of the same class. This is not possible with AspectJ.
  3. Target object is not modified. AspectJ modiefies target object behavior.

It is possible to programmatically create proxies.Cons:

  1. Spring AOP can not be applied to final methods. Spring generates subclass of the target class and weave advuce around overriden method.
  2. Spring only supports method joinpoints. AspectJ and JBoss AOP supports field joinpoints as well.
  3. Targets are not proxied which means that the method calls on this object is not advised.
  4. Lazy initialization of Spring Beans

The lazy initialization of the spring beans is more recommended for the high performance.

  • Every bean must have an id.

Always use id to specify the default name of the bean. If you need characters in your bean name that are not allowed in the id attribute, then you can provide additional names with the name attribute.

  • Full text search

We can use any of the other combination of framework for fastening the Full text searches if any.

· Lucene only· Compass/Lucene· Hibernate Search/Lucene

  • Declarative Caching services for Spring

Declarative Caching Services for Spring provides declarative caching for Spring-powered applications. Declarative caching does not involve any programming and therefore it is a much easier and more rapid way of applying and tuning caching services. Configuration of caching services can be completely done in the Spring IoC container.Provides support for different cache providers such as EHCache, JBoss Cache, Java Caching System (JCS), OSCache, and Tangosol Coherence.Configuration example for this Coherence Cache is

   1: <bean id="customerDaoTarget“
   2:   class="org.springmodules.cache.samples.dao.CustomerDao” />
   3:   <!-- Properties -->
   4: </bean>
   5:  
   6: <coherence:proxy id="customerDao" refId="customerDaoTarget“>
   7:   <coherence:caching methodName="load" cacheName="customerCache" />
   8:   <coherence:flushing methodName="update" cacheNames="customerCache" />
   9: </coherence:proxy>
  10:  
  11: <bean id="customerManager"
  12:   class="org.springmodules.cache.samples.business.CustomerManager" />
  13:   <property name="customerDao" ref="customerDao" />
  14: </bean>

Refer more about this Here

Technorati Tags:,,

Spring Framework : Best Programming Practices.

Spring is a powerful Java application framework, used in a wide range of Java applications. It provides enterprise services to Plain Old Java Objects (POJOs). Spring uses dependency injection to achieve simplification and increase testability. Spring beans, dependencies, and the services needed by beans are specified in configuration files, which are typically in an XML format. The XML configuration files, however, are verbose and unwieldy. They can become hard to read and manage when you are working on a large project where many Spring beans are defined. Spring’s another advantage that it gives more and more support to the other frameworks.Nowadays so many Projects are building on this powerful framework. Although Spring is basically using many Best Practices as well as Design patterns, I think the best way of use of this framework is also necessary for getting all its features and also to get a good performance.

Through this post series I am tried to collect some points which will be good to follow in Spring handling applications. Most of them are used by expert Spring Programmers and came through their experience. The ways I got these points are, through Searching Internet, Referring Spring Official Documentation, Going through Spring Forums, Referring books like Pro Spring from Apress, Spring In Action from Manning and some of them from my own experience. This Series have five posts excluding this. Please note the Spring MVC related points are not included now and will be updated later. Hope this will help you to find Spring Best Practices in one area.

Post 1. Best practices related to Spring Core classes and other utilities.

Post 2. Best practices related to Spring Core & utilities. [Continues …]

Post 3. Data Layer Best Programming Practices.

Post 4. XML Configurations and its best Practices.

Post 5. XML Configurations and its best Practices. [Continues …]

Technorati Tags: , , , ,

Design a site like this with WordPress.com
Get started