AOP(面向切面编程),是一种编程的思想,简单的来说这个AOP就是在不更改原来代码的情况下进行追加功能,相当于我们可以定义一个公共的方法,然后需要的就可以在自己的方法体中,不去new类,就可以调用这个方法在当中
直接上手怎么操作Spring中的AOP
首先从配置开始,我们使用marven中的pom.xml文件中导入aspectjweaver这个包,原本是还需要导入spring-aop包的,但是已经在spring-context这个包下了,所以导入第一个就已经可以使用了。
最开始使用前,我们需要在我们的配置类中添加注解
@Configuration
@ComponentScan(basePackages = "com.itheima")
@EnableAspectJAutoProxy()
public class spring_conf {
//可以判断一下配置成功没
public void user(){
System.out.println("spring is running");
}
}
添加@EnableAspectAutoProxy注解来提醒我们的Spring中有使用AOP注解
原本的SettingDao中是这样的
@Component("settingDao1")
public class SettingDao {
void S(){
System.out.println("the secoundy running");
}
}
我们写一个切面的类,让他切在之前我们使用的SettingDao类中
@Component
@Aspect
public class Aop_test {
@Pointcut("execution(void com.itheima.SettingDao.S())")//切入点
public void pt() {
}
@Before("pt()")
public void method() {
System.out.println("AOP NB");
}
}
解释一下当中的注解,@Aspect是告诉Spring下面的类是用来操作AIO的,@Pointcut是用来定义切入点,中间跟的就是要切进的方法,我们就是切到上面那张图中的S()方法中,但是需要在下面定义一个空方法,@Before,就是说在什么时候在当中放入下面的method方法,@Before就是之前放,@After就是之后放,把那个空方法的名字传进来,就可以使用了
使用测试类测试一下
public class test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(spring_conf.class);
SettingDao ass = (SettingDao)context.getBean("settingDao1");
ass.S();
}
}
不过在之间之后这里,我们官方语言叫做通知类型,通知类型中,通常还有个比较重要的,就是@Around,环绕通知,但是需要在形参的地方添加ProceedingJoinPoint,并调用proceed方法,通常用于拦截器,做校验用的
@Component
@Aspect
public class Aop_test {
@Pointcut("execution(void com.itheima.SettingDao.S())")//切入点
public void pt(){};
@Around("pt()")
public Object method(ProceedingJoinPoint ps) throws Throwable {
System.out.println("AOP NB");
ps.proceed();
System.out.println("AOP a little NB");
return null;
}
}
这样用的,我们需要改变一下返回的类型,这种是无参的,有参数的,前置和后置的通知用joinpoint放在method的形参中接收一下就可以拿到了,主要会用就行