SpringAOP切面方法执行两次的问题,及解决办法。

今天学习了Spring的aop相关内容,在学习中我是先使用的配置文件的方式配置切面和切入点。一开始没有任何问题,后来再使用注解的方式配置的时候就出大问题了。

SpringAOP切面方法执行两次的问题,及解决办法。_第1张图片

如图“开始1”和“结束”字样都是我的切面方法中打印的,“正在添加”是目标方法打印的,也就是说我的切面方法执行了两次。

这下让我彻底蒙了,我查了所有配置都没有问题。

这是我的切面类

import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Util class
 *
 * @author Administrator
 * @date 2018/11/21
 */
@Aspect
@Component
public class AopUtil {
    @Pointcut("execution(void cn.shydl.service.StudentService.insert())")
    public void pointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("开始1");
    }
    @After("pointcut()")
    public void after(){
        System.out.println("结束");
    }
}

这是我的目标类:

package cn.shydl.service;

import org.springframework.stereotype.Service;

@Service
public class StudentService {
    public void insert(){
        System.out.println("正在添加");
    }
    public void delete(){
        System.out.println("正在删除");
    }
}

这是我的配置文件


    
    
    


    
    
    
    
    
        
         
        
        
            
            
        
    

解决办法:

最后查询了许多地方才发现,我的配置文件里切面类有关的那个没有注释,spring实际加载了两遍切面类,所以方法执行了两遍。这个问题也是首次使用spring中出现的第一个问题,以此记录希望帮到大家。

你可能感兴趣的:(入门)