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

本文记录了一个SpringAOP中advice方法执行两次的问题及解决方案。问题出现在同一个类同时被@Component和@Bean注解,导致创建了两个bean,从而产生了两个代理对象,每个代理对象都会执行一次advice。去除@Component或@Bean之一,可以确保advice方法只执行一次。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中遇到某个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其中一个即可。

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值