【问题标题】:Spring Aspect doesn't work if bean is instantiated manually first如果首先手动实例化 bean,则 Spring Aspect 不起作用
【发布时间】:2018-04-29 07:23:50
【问题描述】:

我有一个简单的方面,如下所示

@Aspect
public class PersistentAspect {

    @AfterReturning("@annotation(org.aspect.PersistentOperation)")
    public void log(JoinPoint jp) {
        System.out.println("aspect call");
    }

}

还有一个AppConfig,如下所示

public class AppConfig {

    private Integer num;
    private String text;

    public Integer getNum() {
        return num;
    }

    @PersistentOperation
    public void setNum(Integer num) {

        this.num = num;
    }

    public String getText() {
        return text;
    }

    @PersistentOperation
    public void setText(String text) {

        this.text = text;
    }

}

如下配置类

@EnableWs
@Configuration
public class WsConfig extends WsConfigurerAdapter {

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        AppConfig config = config();
        interceptors.add(new CustomValidatingInterceptor(schema(), null));
    }

    @Bean
    public AppConfig config() {
        AppConfig config = null;
        config = new AppConfig();
        return config;
    }

    @Bean
    public PersistentAspect persistentAspect() {
        PersistentAspect persistentAspect = new PersistentAspect();
        return persistentAspect;
    }
}

如果我在下面使用addInterceptors

AppConfig config = config();

Aspect 将不起作用。我有一个明显的解决方案是将代码更改为

AppConfig config = new AppConfig();

现在我想了解的是,是否有一个配置可以使AppConfig config = config(); 仍然可以工作。我假设当 spring 启动 Bean 时,它可以创建 AppConfig 的 AOP 代理,而当我启动 bean 时,它会以某种方式干扰该过程。 spring/spring-boot 的处理方式是什么?

下面是pom.xml,所以基本上是最新的Spring 5.0.5

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

Edit-1

在发布之前,我已经添加了@EnableAspectJAutoProxy,但这并没有帮助。

尝试该问题的 git repo 在下面

https://github.com/tarunlalwani/spring-aop-so-50084308

【问题讨论】:

    标签: spring spring-boot aspectj spring-aop


    【解决方案1】:

    您的AppConfig bean(您使用@Bean 注释的方法正确初始化)需要包装在代理中,然后执行方面逻辑。

    您必须通过将 @EnableAspectJAutoProxy 注释添加到您的 WsConfig 类来启用此行为。

    顺便说一句:使用是完全正确的

    AppConfig config = config();
    

    在您的 addInterceptors 方法中。 Spring 将返回由 config 方法创建的 bean。

    【讨论】:

    猜你喜欢
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2013-05-12
    • 2018-07-16
    • 2012-01-15
    • 1970-01-01
    相关资源
    最近更新 更多