Archive for September, 2007

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.<bean id=”orderService” class=”com.spring.OrderService” dependency-check=”objects”><property name=”companyName” value=”valuemometum”/><constructor-arg ref=”orderDAO”/></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:<beans><description>This file defines billing servicerelated beans and it depends onbaseServices.xml,which providesservice bean templates…</description>…</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.<bean id=”orderService” class=”com.spring.OrderService”><constructor-arg ref=”orderDAO”/></bean><bean id=”billingService” class=”com.spring.BillingService”><property name=”billingDAO” ref=”billingDAO”></bean>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<beans><description>This file defines billing service related beans and it depends on baseServices.xml,which provides service bean templates…</description>…</beans>Also we can place bean documentation in the description tag.For example<bean id=”aBean” class=”x.y.z.AClass”><description>Bean explanation</description>…</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: -<bean id=”propertyConfigurer” class=”org.springframework.beans. factory.config.PropertyPlaceholderConfigurer”><property name=”location”><value>datasource.properties</value></property></bean><bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”><property name=”url”><value>${database.url}</value></property><property name=”driverClassName”><value>${database.driver}</value></property><property name=”username“><value>${database.user}</value></property><property name=”password”><value>${database.password}</value></property></bean>datasource.properties should contain the following entries:database.url=jdbc:hsqldb:mydbdatabase.driver=org.hsqldb.jdbcDriverdatabase.user=hsqldatabase.password=passwordJndi :<bean id=”myDataSource” class=”org.springframework.jndi.JndiObjectFactoryBean”><property name=”jndiName” value=”jdbc/myDataSource” /></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: , ,

Spring Framework: Best Programming Practices Part 4

 

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

  • Avoid using spring’s ‘autowiring’

Spring can autowire dependencies through introspection of the bean classes so that you do not have to explicitly specify the bean properties or constructor arguments. Bean properties can be autowired either by property names or matching types. Constructor arguments can be autowired by matching types. You can even specify the autodetect autowiring mode, which lets Spring choose an appropriate mechanism. As an example, consider the following:<bean id=”orderService” class=”com..spring.OrderService” autowire=”byName”/>The property names of the OrderService class are used to match a bean instance in the container. Autowiring can potentially save some typing and reduce clutter. However, you should not use it in real-world projects because it sacrifices the explicitness and maintainability of the configurations. Many tutorials and presentations tout autowiring as a cool feature in Spring without mentioning this implication. In my opinion, like object-pooling in Spring, it is more a marketing feature. It seems like a good idea to make the XML configuration file smaller, but this will actually increase the complexity down the road, especially when you are working on a large project where many beans are defined. Spring allows you mix autowiring and explicit wiring, but the inconsistency will make the XML configurations even more confusing.

  • Use naming conventions

This is the same philosophy as for Java code. Using clear, descriptive, and consistent name conventions across the project is very helpful for developers to understand the XML configurations. For bean ID, for example, you can follow the Java class field name convention. The bean ID for an instance of OrderServiceDAO would be orderServiceDAO.For large projects; you can add the package name as the prefix of the bean ID.

  • Use shortcut forms

The shortcut form is less verbose, since it moves property values and references from child elements into attributes. For example, the following:<bean id=”orderService” class=”com.spring.OrderService”><property name=”companyName”><value>valuemometum</value></property><constructor-arg><ref bean=”orderDAO”></constructor-arg></bean>Can be rewritten in the shortcut form as:<bean id=”orderService” class=”com.spring.OrderService”><property name=”companyName” value=” valuemometum “/><constructor-arg ref=”orderDAO”/></bean>The shortcut form has been available since version 1.2. Note that there is no shortcut form for <ref local=”…”>.The shortcut form not only saves you some typing, but also makes the XML configuration files less cluttered. It can noticeably improve readability when many beans are defined in a configuration file.

  • Prefer type over index for constructor argument matching

Spring allows you to use a zero-based index to solve the ambiguity problem when a constructor has more than one arguments of the same type, or value tags are used. For example, instead of:<bean id=”billingService” class=”com.spring.BillingService”><constructor-arg index=”0″ value=”valuemometum”/><constructor-arg index=”1″ value=”100″/></bean>It is better to use the type attribute like this:<bean id=”billingService” class=”com.spring.BillingService”><constructor-arg type=”java.lang.String” value=”valuemometum”/><constructor-arg type=”int” value=”100″/></bean>Using index is somewhat less verbose, but it is more error-prone and hard to read compared to using the type attribute. You should only use index when there is an ambiguity problem in the constructor arguments.

  • Reuse bean definitions, if possible

Spring offers an inheritance-like mechanism to reduce the duplication of configuration information and make the XML configuration simpler. A child bean definition can inherit configuration information from its parent bean, which essentially serves as a template for the child beans. This is a must-use feature for large projects. All you need to do is to specify abstract=true for the parent bean, and the parent reference in the child bean. For example:<bean id=”abstractService” abstract=”true” class=”com.spring.AbstractService”><property name=”companyName” value=”valuemometum”/></bean><bean id=”shippingService” parent=”abstractService” class=”com.spring.ShippingService”><property name=”shippedBy” value=”valuemometum”/></bean>The shippingService bean inherits the value valuemometum for the companyName property from the abstractService bean. Note that if you do not specify a class or factory method for a bean definition, the bean is implicitly abstract.

  • Prefer assembling bean definitions through ApplicationContext over imports

Like imports in Ant scripts, Spring import elements are useful for assembling modularized bean definitions. For example:<beans><import resource=”billingServices.xml”/><import resource=”shippingServices.xml”/><bean id=”orderService” class=”com.spring.OrderService”/><beans>However, instead of pre-assembling them in the XML configurations using imports, it is more flexible to configure them through the ApplicationContext. Using ApplicationContext also makes the XML configurations easy to manage. You can pass an array of bean definitions to the ApplicationContext constructor as follows:String[] serviceResources = {”orderServices.xml”, “billingServices.xml”,”shippingServices.xml”};ApplicationContext orderServiceContext = new ClassPathXmlApplicationContext(serviceResources);

Technorati Tags: , ,

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:<beans><bean id=”aBeanId”class=”org.springframework.context.support.ClassPathXmlApplicationContext”><constructor-arg><list><value>/spring/applicationContext-forAllTheEnvironments.xml</value><value>/spring/applicationContext-local.xml</value></list></constructor-arg><constructor-arg><ref bean=”frameworkApplicationContextId”/></constructor-arg></bean></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:<bean id=”crudInterceptor” class=”com.mycompany.CrudInterceptor”/><bean id=”crud”class=”org.springframework.aop.support.RegexpMethodPointcutAdvisor”><property name=”advice”><ref local=” crudInterceptor “/></property><property name=”patterns”><value>.*create.*,.*destroy.*,.*get.*,.*update.*</value></property></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:<bean id=”myProxy” class=”org.springframework.aop.framework.ProxyFactoryBean” abstract=”true”><property name=”interceptorNames”><list><value>interceptor1</value><value>interceptor2</value></list></property></bean><bean id=”mybean” parent=”myProxy”><property name=”proxyInterfaces”><value>com.mycompany.mybean</value></property><property name=”target”><bean class=”com.mycompany.MyBeanImpl”><property name=”name”><value>Dave</value></property><property name=”description”><value>Good Boy</value></property></bean></property></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 :<bean id=”bnProxyCreator” class=”org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator”><property name=”beanNames”><value>bean1,mybean*</value></property><property name=”interceptorNames”><list><value>advisor1</value><value>interceptor1</value></list></property></bean>DefaultAdvisorAutoProxyCreator :<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:<bean id=”businessBean” class=”org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource”><props><prop key=”businessMethod1″>PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ,-RollBackBusinessException</prop></props></property> </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:public class CountingMethodAdvice implements MethodInterceptor {// The next serial number to be assignedprivate static long nextSerialNum = 0;private static ThreadLocal serialNum = new ThreadLocal() {protected synchronized Object initialValue() {return new Long(nextSerialNum++);}};private static long getCount() {if(serialNum!=null){return ((Long) (serialNum.get())).longValue();}}public Object invoke(MethodInvocation methodInvocation) throws Throwable {System.out.println(”This method is called ” + getCount + ” times”);}}

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

<bean id="customerDaoTarget
  class="org.springmodules.cache.samples.dao.CustomerDao” />
  <!-- Properties -->
</bean>
<coherence:proxy id="customerDao" refId="customerDaoTarget“>
  <coherence:caching methodName="load" cacheName="customerCache" />
  <coherence:flushing methodName="update" cacheNames="customerCache" />
</coherence:proxy>


<bean id="customerManager"
  class="org.springmodules.cache.samples.business.CustomerManager" />
  <property name="customerDao" ref="customerDao" />
</bean>

Refer more about this Here

Technorati Tags:,,

Next Page »


View Lijin Joseji's profile on LinkedIn

Disclaimer

The information on this site is for informational purposes only. The use of any Trademark or Copyrighted material is not intended to infringe Copyright. This blog is intended to be used under a policy of personal and non commercial use.

Adds

Add to Google

Blog Stats

  • 105,969 hits

Categories