Spring AOP 使用注解为API引入新功能

来源:互联网 发布:java中1到100的质数 编辑:程序博客网 时间:2024/06/12 00:52
为一个已知的API添加一个新的功能。
由于是已知的API,我们不能修改其类,只能通过外部包装。但是如果通过之前的AOP前置或后置通知,又不太合理,最简单的办法就是实现某个我们自定义的接口,这个接口包含了想要添加的方法。
但是JAVA不是一门动态的语言,无法再编译后动态添加新的功能,这个时候就可以使用 aop:declare-parents 来做了。


原API(在此没有使用接口):


public interface PerformerService{
public void perform();
}


@Service
public class PerformerServiceImpl implements PerformerService{

public void perform(){
System.out.println("The show is start");
}
}


新增接口


public interface ActionService(){
public void bow();
}


public class ActionServiceImpl(){
public void bow(){
System.out.println("Thanks for coming!");
}
}




引入接口切面
@Service
public Class Introducer(){
//混入接口 value="要被引入的接口实现类" defaultImpl="引入的接口实现类"
@DeclareParents(value="com.stru.service.PerformerServiceImpl",
defaultImpl=ActionServiceImpl.class)
public static ActionService actionService;//引入的接口
}


测试


public class Test1 {


public static void main(String args[]){

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
PerformerService performerService = (PerformerService) ac.getBean("performerServiceImpl");
performerService.perform();
ActionService actionService = (ActionService)ac.getBean("performerServiceImpl");
actionService.bow();
}

}
0 0
原创粉丝点击