springAOP advice方法执行两次 解决方法

项目中遇到某个Aspect类中全部advice方法都会执行两次的情况,现在问题记录,供大家参考;

首先将问题所在标出来讲述问题,

@Aspect
@Component
public class AopTest {

    @Pointcut("execution(** com.bean.Person.eat(..) )")
    public void eat(){}
    
    @Before("execution(** com.bean.Person.eat(..) )")
    public void wash(){
        System.out.println("洗手");
    }
    @After("eat()")
    public void afterWash(){
        System.out.println("再洗手");
    }
}   

测试bean :

@Component
public class Person {
    private String name;
    private int age;
    
    public void eat (){
        System.out.println(name +" 在 吃");
    }
    
    public Person() {
        super();
    }

}

配置:

@Configuration
@ComponentScan
public class SpringBeanConfigFlag {

    
    @Bean
    public Person getPerson(){
        return new Person("alix",18);
    }
    
    @Bean
    public AopTest getAopTest(){
        return new AopTest();
    }

 }

测试类:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.bean.ICar;
import com.bean.Person;
import com.config.spring;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = spring.class)
public class test {

    @Autowired
    Person person;
    @Autowired
    ICar car;
    
    @Test
    public void test0() {
        person.eat();
   
    }
   
}

运行结果:

结果显示springAOP  adviced方法执行了两次, 现在说一下问题所在, 首先请注意标红的地方,@Component 和@bean   ,就是因为创建了两次bean,创建两个代理(这里成为代理1和代理2,而代理2 有代理了代理1),所以adviced方法执行两次,只需去除@Component 和@bean其中一个即可。

此为原创,转载请注明转载地址。

你可能感兴趣的:(springAOP advice方法执行两次 解决方法)