通过Spring Aop编程思想,利用注解为某些对象添加新的功能
2017-09-18 15:36
585 查看
通过Spring Aop编程思想,利用注解为某些对象添加新的功能
我们在利用Spring Aop的时候已经利用了切面来为原有的Bean中的方法新增了额外功能。那么我们也可以利用这个思路创建一个切面来为已有的Bean增点额外的功能(额外的方法)以下是展示它是如何工作的
为了验证改思路是行的通,我们直接贴代码(亲测)
//方式一:利用注解 //引入bean public interface Encoreable(){ //被引入的新曾方法 void performance(); } //引入bean的实现类 @Service public class DefaultEncoreable implements Encoreable { @Override public void encoreable() { System.err.println("利用aop注解为对象增减新功能成功了"); } } public interface PerformService { public void perform(int a); } @Service public class PerformServiceImpl implements PerformService{ @Override public void perform(int a){ System.err.println("11111111111111111"); } } //验证调用结果 public class AopT extends BaseTest{ @Resource private PerformService performService; @Test public void get(){ Encoreable encoreable = (Encoreable)performService; encoreable.encoreable(); } } @Aspect //当spring发现有一个此注解的时候,就会创建一个代理类然后将调用委托给被被代理的bean或者被引入的实现 public class EncoreableIntroducer(){ @DeclarParents(value="xx.xx.Performance+",defaultImpl=DefaultEncoreable.class) public static Encoreable encoreable; } //与之前的切面一样要在Spring的配置文件里声明这个需要需要创建代理Bean的Bean <bean class="xx.xx.EncoreableIntroducer"></bean> //方式二:利用spring配置文件 <aop:config> <aop:aspect> <aop:declare-parents types-matching="xx.xx.Performance+" implement-interface="xx.xx.xx.Encoreable" default-impl="encoreableDelegate" /> </aop:aspect> </aop:config> <bean id="encoreableDelegate" class="xx.xx.DefaultDecoreable"></bean>
可以看到EncoreableIntroducer是一个切面,但是他与我们熟知的切面不同,没有前置,后置,或者环绕的额外功能,但是通过@DeclarParents注解可以将Encoreable接口引入到Performance bean中
@DeclarParents注解由三部分组成
value:属性指的是那种类型的bean要引入该接口,在本例子中也就是所有的实现了Performance接口的Bean,”+”标识表示的是Performance的子类型而不是自己。
defaultImpl:属性指定了为引入功能提供的实现类,改例子中用DefaultEncoreable作为实现类
@DeclarParents标注的静态属性指明了要引入的接口,在本例子中我们引入的是Encoreable 接口。
相关文章推荐
- 利用Spring AOP和自定义注解实现日志功能
- 利用Spring AOP与action注解为系统增加日志功能
- 简单模拟Spring AOP功能 (1) AOP编程思想的理解
- Spring面向切面编程——Spring实现AOP方式——通过注解实现
- 利用Spring AOP与JAVA注解为系统增加日志功能
- spring使用AOP和自定义注解功能添加日志管理--实用
- Spring系列之 (十六):利用Spring AOP和自定义注解实现日志功能
- 利用Spring的AOP编程和JAVA自定义注解,实现Web项目的HTTP请求头域检测
- 从头认识Spring-3.8 简单的AOP日志实现(注解版)-扩展添加检查订单功能,以便记录并检測输入的參数
- spring添加<aop:aspectj-autoproxy>让注解自为类生成代理对象时出错
- Spring 通过注解方式实现AOP切面编程
- Spring 通过AOP 来实现前置,环绕,异常通知,注解
- Spring+SpringMVC+Mybatis 利用AOP自定义注解实现可配置日志快照记录
- Spring aop 通过获取代理对象实现事务切换
- 如何:通过使用 Visual C# 2010 功能访问 Office 互操作对象(C# 编程指南)
- spring aop 功能初次使用(注解方式)
- 【Spring实战】—— 11 通过AOP为特定的类引入新的功能
- spring学习(五)—通过注解方式创建对象和注入属性
- Spring AOP之通过注解编写AOP
- 利用Spring AOP处理自定义注解