需求分析:现在有一个接口实现类SomeServiceImpl,继承了一个抽象方法dosome,需要在不改实现类SomeServiceImpl的条件下为dosome方法添加功能,使得在dosome方法执行前会先打印前置方法。
(1) maven 依赖
junit junit4.11 test org.springframework spring-context5.2.5.RELEASE org.springframework spring-aspects5.2.5.RELEASE
(2)doSome方法
public class SomeServiceImpl implements SomeService {
@Override
public void doSome(String name,Integer age) {
System.out.println("执行了dosome方法");
}
}
(3)定义切面类
@Aspect
public class MyAspect {
@Before(value = "execution(public void org.example.ba01.SomeServiceImpl.doSome(..))")
public void before(){
System.out.println("前置方法");
}
}
(4)applicationContext.xml
//声明自动代理生成器,会扫描容器中的切面类
(5)测试方法
public class AppTest
{
@Test
public void shouldAnswerWithTrue()
{
String config="applicationContext.xml";
ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
SomeService proxy=(SomeService)ctx.getBean("someService");
proxy.doSome("lisi",20);
}
}
成功
这种编程方式有什么好处呢,解耦合、减少代码重复,试想,如果你有一百个方法需要添加某种同样的功能,你不可能都去方法源代码中实现吧?利用面向切面编程的思想,可以达到一劳永逸的效果!



