Spring 4: 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.

<pre> @Component @Scope("request") public interface @Model{ } </pre>

@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.

<pre> @Model public class MyModel{ } </pre>

Another example, a @Repository class with @Transactional support.

<pre> @Repository @Transactional public class SignupRepository{ } </pre>

The @Repository and @Transactional can be extracted into a new annotation named @TransactionalRepository.

<pre> @Repository @Transactional public @interface TransactionalRepository{} </pre>

And apply the new @TransactionalRepository annotation on your repository class directly.

<pre> @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); } } </pre>

Test code.

<pre> @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")); } </pre>

Check out the codes from my github.com, https://github.com/hantsy/spring4-sandbox.

转载于:https://my.oschina.net/hantsy/blog/292996

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值