Over a million developers have joined DZone.
Silver Partner

Avoid Spring Annotation Code Smell: Use Spring 3 Custom Annotations

· Java Zone

With Spring 3, annotations are becoming the defacto standard for defining bean configuration. Annotations like @Configuration, @Bean allow you to create externalized configuration definitions in Java. It is equivalent to the configuration we define in XML. But as we use annotations, we start duplicating these annotations in different classes. For example, our UserService will have following declaration

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public class UserService {

}

In this bean definition we have configured UserService as a service component with prototype scope, with readonly transactions which will get roll-backed for RuntimeException. As our application evolves, we will have other classes with the same set of annotations  like

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public class RoleService {

}

This is a sort of code smell, as we are duplicating the same set of annotations in different classes. If, in future, we decide to change the transaction strategy i.e. making readonly equal to false, then we have to make changes in all the classes (supposing you need the same configuration in all classes). This type of problem can be solved by defining your own custom annotations. Custom annotations have different annotations applied to them. So, in our application we can have our own service annotation like

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public @interface ReadOnlyService{

}

The best part of using custom annotations is that you don't have to make any configuration, Spring will auto detect that these beans are service components and everything will work fine. Custom Annotations are a very small feature added in Spring but are very useful. Next time you see your annotations code smell think about using custom annotations.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}