Spring AOP之Introduction(@DeclareParents)简介

  Spring的文档上对Introduction这个概念和相关的注解@DeclareParents作了如下介绍:
  Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare that advised objects implement a given interface, and to provide an implementation of that interface on behalf of those objects.
An introduction is made using the @DeclareParents annotation. This annotation is used to declare that matching types have a new parent (hence the name).
 
  在这段介绍之后还给出了一个例子,对于初学者要理解这段话以及后面的例子还是蛮困难的,因此下面用一个简单的例子告诉大家什么是Introduction以及如何使用@DeclareParents注解。
  对于Introduction这个词,个人认为理解成引入是最合适的,其目标是对于一个已有的类引入新的接口(有人可能会问:有什么用呢?简单的说,你可以把当前对象转型成另一个对象,那么很显然,你就可以调用另一个对象的方法了),看一个例子就全明白了。
  假设已经有一个UserService类提供了保存User对象的服务,但是现在想增加对User进行验证的功能,只对通过验证的User提供保存服务,在不修改UserService类代码的前提下就可以通过Introduction来解决。

  首先定义一个Verifier接口,里面定义了进行验证的方法validate(),如下所示

1 public interface Verifier {
2     public boolean validate(User user);
3 }

  接下来给出该接口的一个实现类BasicVerifier,如下所示

1 public class BasicVerifier implements Verifier {
2     @Override
3     public boolean validate(User user) {
4         if(user.getUsername().equals("jack") && user.getPassword().equals("1234")) {
5             return true;
6         }
7         return false;
8     }
9 }

  如何才能为UserService类增加验证User的功能呢,如下所示定义Aspect:

1 @Aspect
2 @Component
3 public class MyAspect {
4     @DeclareParents(value="com.tsinghuait.services.UserService", 
5             defaultImpl=com.tsinghuait.aop.BasicVerifier.class)
6     public Verifier verifer;
7 }

  接下来就可以将UserService对象转型为Verifier对象并对用户进行验证了,如下所示:

 1 class Test {
 2 
 3     public static void main(String[] args) {
 4         User user1 = new User();
 5         user1.setUsername("abc");
 6         user1.setPassword("def");
 7         
 8         ApplicationContext factory = new ClassPathXmlApplicationContext("config.xml");
 9         Service s = (Service) factory.getBean("service");
10         Verifier v = (Verifier) s;
11         if(v.validate(user1) {
12             System.out.println("验证成功");
13             s.serve(user1);
14         }
15         
16     }
17 }

  这样,上面代码中的user1是不会被服务的,当然是因为没有通过验证啦!
  这样一说,是不是大概明白什么是Introduction了呢,其实@DeclareParents用起来也很简单吧!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值