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.
- To prevent long argument lists for constructors.
- To prevent argument lists for constructors with arguments of the same type.
- 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:
- Spring AOP doesn’t require any special java compiler or special build process. AspectJ requires special compiler.
- Different advice could be applied to different instance of the same class. This is not possible with AspectJ.
- Target object is not modified. AspectJ modiefies target object behavior.
It is possible to programmatically create proxies.Cons:
- Spring AOP can not be applied to final methods. Spring generates subclass of the target class and weave advuce around overriden method.
- Spring only supports method joinpoints. AspectJ and JBoss AOP supports field joinpoints as well.
- Targets are not proxied which means that the method calls on this object is not advised.
- 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
Refer more about this Here