meta annotation
#Meta annotation
If you have used CDI(introduced in Java EE 6), you could have been impressed by its stereotype feature. With a @Stereotype
annotation, you can combine different concerns into one annotation and get both effectiveness when applied it in your classes.
In fact, in Spring world, this feature was existed for a long time, but it is not flexible as CDI.
Explore the codes of the @Controller
, @Repository
, and @Service
, you can find they are all derived from the @Component
annotation which is use for declaring a Spring managed bean.
But unfortunately, besides these annotations, you can not combine different annotations freely as CDI does. Thing has been changed when Spring 4 was born.
In Spring 4, you can combine different annotations into a new custom annotation freely.
For example, Spring 4 introduced a new annotation @RestController
, which is just a combination of @Controller
and @ResponseBody
.
You can create your annotation like this, eg.
@Component @Scope("request") public interface @Model{ }
@Model
annotation is a combination of @Component
and @Scope
, you can apply it on your new Java class, which indicates it is a request scoped component.
@Model public class MyModel{ }
Another example, a @Repository
class with @Transactional
support.
@Repository @Transactional public class SignupRepository{ }
The @Repository
and @Transactional
can be extracted into a new annotation named @TransactionalRepository
.
@Repository @Transactional public @interface TransactionalRepository{}
And apply the new @TransactionalRepository
annotation on your repository class directly.
@TransactionalRepository public class SignupRepository{ @PersistenceContext private EntityManager em; public Long save(Signup entity) { em.persist(entity); return entity.getId(); } public Signup findById(Long id) { return em.find(Signup.class, id); } }
Test code.
@Test public void testSignup() { log.debug("call testSignup CURD@@@"); Signup entity = new Signup("Hantsy", "Bai", "hantsy@gmail.com"); Long savedId = signupRepository.save(entity); log.debug("saved id@" + savedId); assertTrue(savedId != null); Signup signup=signupRepository.findById(savedId); assertTrue(signup.getFirstName().equals("Hantsy")); }
Check out the codes from my github.com, https://github.com/hantsy/spring4-sandbox.