gpt4 book ai didi

java - Spring MVC 与 AspectJ

转载 作者:行者123 更新时间:2023-11-30 02:29:07 25 4
gpt4 key购买 nike

我有一个正在运行的 spring mvc 项目。我想使用 AspectJ 通过我的 Controller 记录每个请求。相关代码:

Controller :(在 hu.freetime.controller 包中)

@Controller
@RequestMapping("/")
public class BaseControllerImpl {
@RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
return "index";
}
}

方面:

@Aspect
public class ControllerAspectImpl {
Logger logger = LoggerFactory.getLogger(ControllerAspectImpl.class);

@Pointcut("execution(public * hu.freetime.controller.BaseControllerImpl.*(..))")
public void logController() {
}


@Around("logController()")
public void log(final ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
logger.info("Calling Controller method: " + method.getName() + "()");
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
}
}

WebAppInitializer:

public class CashflowWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

WebConfig 类:

@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "hu.freetime.controller", "hu.freetime.aspect" })
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}

@Bean
public ControllerAspectImpl getControllerAspect() {
return new ControllerAspectImpl();
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}

问题是,这两个组件中只有一个在工作。如果我“关闭”AOP,MVC 工作得很好,但是当我“打开”并且我想转到主页时,我收到此错误:

HTTP Status 404 - .../WEB-INF/views/.jsp
The requested resource is not available.

奇怪的是,它想要映射“.jsp”而不是“index.jsp”,正如我在 Controller 的index()方法中所写的那样。我在运行时调试,它确实停在 Controller 方法处。

我怎样才能让它发挥作用?

最佳答案

您的周围建议不会返回 pjp.proceed() 的结果。这是建议方法的返回值,并且必须由建议返回!否则您也会将建议方法变成无效。

public **Object** log(final ProceedingJoinPoint pjp) {
...
try {
**return** pjp.proceed(); <<< !
} catch (Throwable e) {
e.printStackTrace();
}
}

关于java - Spring MVC 与 AspectJ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com