方面未在 Spring 中执行

发布于 2025-01-06 22:52:23 字数 1922 浏览 0 评论 0原文

我正在编写一个几乎完全受登录保护的网站(我正在使用 Spring Security)。不过,有些页面不受保护(主页、登录页面、注册页面、忘记密码页面等),我想要实现的是:

  • 如果用户在访问这些非页面时未登录,受保护的页面, 正常显示
  • 如果用户已经登录,则重定向到 主页(或到 redirectTo 注释元素中指定的页面)

当然我想避免将其放入每个控制器方法中:

if(loggedIn())
{
    // Redirect
}
else
{
    // Return the view
}

因此我想使用 AOP。

我创建了注释 @NonSecured 并编写了以下方面:

@Aspect
public class LoggedInRedirectAspect
{
    @Autowired
    private UserService userService;

    @Around("execution(@my.package.annotation.NonSecured * *(..))")
    public void redirect(ProceedingJoinPoint point) throws Throwable
    {
        System.out.println("Test");
        point.proceed();
    }
}

示例注释方法:

@Controller
@RequestMapping("/")
public class HomeController
{
    @NonSecured(redirectTo = "my-profile")
    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model,
                        HttpServletRequest request) throws Exception
    {
        // Show home page
    }
}

applicationContext.xml 重要位:

<context:annotation-config />
<context:component-scan base-package="my.package" />

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

<bean id="loggedInRedirectAspect" class="my.package.aspect.LoggedInRedirectAspect" />
<aop:aspectj-autoproxy proxy-target-class="true">
    <aop:include name="loggedInRedirectAspect" />
</aop:aspectj-autoproxy>

问题是方法 redirect(...) 中该方面永远不会被调用。 方面通常工作正常,实际上方面中的以下方法将被调用: 以下建议被调用,但不会为控制器方法调用。

@Around("execution(* *(..))")
public void redirect(ProceedingJoinPoint point) throws Throwable
{
    point.proceed();
}

我在切入点中做错了什么吗?

谢谢。

更新:这个问题中的最后一个代码片段被调用,但仍然没有被控制器方法调用。

I'm coding a website that will be almost fully protected by login (I'm using Spring Security for it). There are certain pages that are not protected, though (home page, login page, registration page, forgotten password page, ...) and what I'm trying to achieve is:

  • If the user is not logged in when accessing these non-secured pages,
    show them normally
  • If the user is already logged in, redirect to the
    home page (or to the page specified in the redirectTo annotation element)

Of course I want to avoid to put this in every single controller method:

if(loggedIn())
{
    // Redirect
}
else
{
    // Return the view
}

And for this reason I would like to use AOP.

I created the Annotation @NonSecured and I coded the following Aspect:

@Aspect
public class LoggedInRedirectAspect
{
    @Autowired
    private UserService userService;

    @Around("execution(@my.package.annotation.NonSecured * *(..))")
    public void redirect(ProceedingJoinPoint point) throws Throwable
    {
        System.out.println("Test");
        point.proceed();
    }
}

Example annotated method:

@Controller
@RequestMapping("/")
public class HomeController
{
    @NonSecured(redirectTo = "my-profile")
    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model,
                        HttpServletRequest request) throws Exception
    {
        // Show home page
    }
}

applicationContext.xml important bits:

<context:annotation-config />
<context:component-scan base-package="my.package" />

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

<bean id="loggedInRedirectAspect" class="my.package.aspect.LoggedInRedirectAspect" />
<aop:aspectj-autoproxy proxy-target-class="true">
    <aop:include name="loggedInRedirectAspect" />
</aop:aspectj-autoproxy>

The problem is that the method redirect(...) in the aspect never gets called. Aspects in general are working fine, in fact the following method in the aspect will get called: The following advice gets called but doesn't get called for the controller methods.

@Around("execution(* *(..))")
public void redirect(ProceedingJoinPoint point) throws Throwable
{
    point.proceed();
}

Am I doing something wrong in my pointcut?

Thank you.

Update: the last snippet in this question gets called but still doesn't get called for the controller methods.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小情绪 2025-01-13 22:52:23

@satoshi,我认为您遇到的问题是因为您使用的是Spring-AOP,它只能为具有接口的bean创建AOP代理 - 在您的情况下,控制器没有接口。

修复方法可能是使用 AspectJ 进行编译时/加载时编织,而不使用 Spring AOP 或在类路径中包含 cglib jar 并强制创建基于 cglib 的代理:

<aop:aspectj-autoproxy proxy-target-class="true"/>

更新:
编译时编织可以使用 maven 插件完成,showWeaveInfo 配置将准确显示哪些类已被编织:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.6.10</version>
        </dependency>
    </dependencies>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <outxml>true</outxml>
        <verbose>true</verbose>
        <showWeaveInfo>true</showWeaveInfo>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>

@satoshi, I think the problem that you are having is because you are using Spring-AOP and it can create AOP proxies only for beans with interfaces - and in your case the controllers do not have an interface.

The fix could be to use compile time/load time weaving using AspectJ and to not use Spring AOP OR to have cglib jars in the classpath and to force cglib based proxy creation :

<aop:aspectj-autoproxy proxy-target-class="true"/>

Update:
Compile time weaving can be done using a maven plugin, the showWeaveInfo configuration will show exactly which of the classes have been weaved:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.6.10</version>
        </dependency>
    </dependencies>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <outxml>true</outxml>
        <verbose>true</verbose>
        <showWeaveInfo>true</showWeaveInfo>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>
自此以后,行同陌路 2025-01-13 22:52:23

通常我会使用拦截器而不是用于此目的的方面。例如,创建一个 RequestInitializeInterceptor 它将检查安全主体并相应地重定向。对于这项工作来说,Aspects 有点大材小用了。拦截器将充当针对特定控制器的每个请求的前端控制器,并决定是否允许传输该请求。

 public class RequestInitializeInterceptor extends HandlerInterceptorAdapter {

  // Obtain a suitable logger.
  private static Log logger = LogFactory
      .getLog(RequestInitializeInterceptor.class);

  /**
   * In this case intercept the request BEFORE it reaches the controller
   */
  @Override
  public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) throws Exception {
    try {

      logger.info("Intercepting: " + request.getRequestURI());

      // Your logic to redirect accordingly
     if (userAuthenticated) {
       response.sendRedirect(URL);
       return false;
    }
      return true;
    } catch (SystemException e) {
      logger.info("request update failed");
      return false;
    }
  }
}

希望这有帮助。

Usually what I would use an interceptor and not an aspect for this purpose. For example, create a RequestInitializeInterceptor which would check the security principal and redirect accordingly. Aspects is an overkill for this job. The interceptor will act as a front controller for every request to specific controllers and decide if it is allowed to transfer the request or not.

 public class RequestInitializeInterceptor extends HandlerInterceptorAdapter {

  // Obtain a suitable logger.
  private static Log logger = LogFactory
      .getLog(RequestInitializeInterceptor.class);

  /**
   * In this case intercept the request BEFORE it reaches the controller
   */
  @Override
  public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) throws Exception {
    try {

      logger.info("Intercepting: " + request.getRequestURI());

      // Your logic to redirect accordingly
     if (userAuthenticated) {
       response.sendRedirect(URL);
       return false;
    }
      return true;
    } catch (SystemException e) {
      logger.info("request update failed");
      return false;
    }
  }
}

Hope this helps.

拥抱影子 2025-01-13 22:52:23

对我有用的方法,请检查以下几点:

  • aspectjweaver.jar 位于类路径中(版本 1.6.8 或更高版本)
  • Aspect 类使用 @Aspect< 进行注释/code> 和 @Component
  • 您启用了 springspectJ-auto-proxy

Java 配置:

@Configuration
@ComponentScan("io.mc.springaspects")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}

方面:

@Aspect
@Component
public class AnnotationAspect {
   ...
}

Maven:

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.9</version>
</dependency>

What worked for me, please check following points:

  • aspectjweaver.jar is on classpath (version 1.6.8 or later)
  • Aspect class is annotated with both @Aspect and @Component
  • You enabled spring aspectJ-auto-proxy

Java config:

@Configuration
@ComponentScan("io.mc.springaspects")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}

Aspect:

@Aspect
@Component
public class AnnotationAspect {
   ...
}

Maven:

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.9</version>
</dependency>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文