AOP面向切面编程
导读:曾经在学习Java的时候,我们刚开始接触到的是OOP面向对象的思想。
OOP:面向对象编程-我们定义一个类,在里面设置一些属性、方法,我们在其他类只需要new
一下对象就能访问类的属性、方法。
何为面向切面编程呢AOP?
AOP:面向切面编程-我们定义了很多类(A、B类),这些类里面有很多方法,这个时候我们在不去动这些源代码的情况下去增加功能,增加业务,我们会设置一个 切面类(C类),在这个类里增加我们需要的新功能。
AOP的实现方式?
通过框架aspectj
实现。
案例:
定义如下结构:
public interface UsbInterface {
void work();
}
@Component
public class Phone implements UsbInterface{
@Override
public void work() {
System.out.println("this is a phone");
}
}
@Component
public class Camera implements UsbInterface{
@Override
public void work() {
System.out.println("this is a camera");
}
}
定义切面类:SmartTechAspect
@Aspect
@Component
public class SmartTechAspect {
//AOP切入表达式
@Before(value="execution(public void com.linghu.aop.usb.Phone.work())")
public void showBeginLog(JoinPoint joinPoint){
System.out.println("前置通知-日志信息~");
Signature signature = joinPoint.getSignature();
System.out.println("日志-方法名:"+signature.getName());
}
@After(value = "execution(public void com.linghu.aop.usb.Camera.work())")
public void showFinallydLig(JoinPoint joinPoint){
System.out.println("后置通知信息~");
Signature signature = joinPoint.getSignature();
System.out.println("日志-方法名:"+signature.getName());
}
}
在这里 @Aspect
就说明该类是一个切面类,再通过 @Component
将该类自动注入容器。
@Before
表示前置通知, value="execution(public void com.linghu.aop.usb.Phone.work())"
表示将方法 showBeginLog()
插入到 com.linghu.aop.usb.Phone.work()
之前。
这里要认识到:
- 前置通知:
@Before
- 返回通知:
@AfterReturning
- 异常通知:
@AfterThrowing
- 后置通知:
@After
- 环绕通知:
@Around
一定要做的bean处理:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.linghu.aop.usb"/>//自动扫描包
<aop:aspectj-autoproxy/>
</beans>
<aop:aspectj-autoproxy/>
一定要添加,它表示开启注解AOP的功能,有了它,切面类的@Aspect
注解才能起作用。
做一下测试:
public class AopAspectjTest {
@Test
public void phoneTestByProxy() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
//通过接口来
UsbInterface phone = (UsbInterface) ioc.getBean("phone");
UsbInterface camera = (UsbInterface) ioc.getBean("camera");
phone.work();
camera.work();
System.out.println("-----------------");
}
}