【问题标题】:Spring aop aspects not executing on annotationsSpring aop 方面未在注释上执行
【发布时间】:2016-08-15 18:44:40
【问题描述】:

我正在使用 spring 开发一个 WebSocket 服务器应用程序。 类 PlayerHandler

import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * Created by kris on 11.07.16.
 */
public class PlayerHandler extends TextWebSocketHandler{
    public PlayerHandler(){}

    @Override
    @AuthorizationRequired
    public void handleTextMessage(WebSocketSession session, TextMessage tm) throws IOException {
        session.sendMessage(tm);
    }
}

我希望用户通过令牌获得每个传入请求的授权,因此我创建了一个 Aspect UserAuthorization

package com.berrigan.axevor.authorization;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class UserAuthorization {
    @Around("@annotation(com.berrigan.axevor.authorization.AuthorizationRequired)")
    public void authorize(ProceedingJoinPoint jp) throws Throwable{
         System.out.println("\n\n\n\n\Works\n\n\n\n\n\n");
        jp.proceed();
    }
}

我添加了@AuthorizationRequired 注释,它指示用户将被授权的方法。不幸的是,方法授权永远不会被调用。我在主类中添加了以下代码来检查 bean 是否被创建。

UserAuthorization ua = ctx.getBean(UserAuthorization.class); // ApplicationContext
if(au == null) System.out.println("is null")

但我没有得到这样的日志。 我的弹簧配置

@EnableAutoConfiguration
@Configuration
@EnableAspectJAutoProxy
@Import({com.berrigan.axevor.websocket.WebSocketConfig.class})
@ComponentScan(basePackages = {"com.berrigan.axevor"})
public class Config {}

注释代码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AuthorizationRequired{}

@配置 @EnableWebSocket

public class WebSocketConfig implements WebSocketConfigurer{
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry){
        registry.addHandler(playerHandler(), "/game").setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler playerHandler(){
        return new PlayerHandler();
    }
}

【问题讨论】:

  • 让我们看看你的注释。在您使用时发布minimal reproducible example
  • 是的,这对我来说一切正常,有一些基本假设。请发帖minimal reproducible example
  • 这段代码应该是可以运行的,我是用spring-boot来运行的
  • 您没有显示PlayerHandler 的 bean 声明或您如何检索和使用该 bean。我们不知道WebSocketConfig 和所有其他类型是什么。
  • 编辑的答案,它只是标准的 websocket 配置

标签: java spring aop spring-aop


【解决方案1】:

找到解决方案,损坏的 pom.xml 文件。重新生成后,一切都像魅力一样发挥作用

【讨论】:

    猜你喜欢
    • 2011-09-20
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多