gpt4 book ai didi

java - Rest + Spring AOP + 接口(interface)不注入(inject)

转载 作者:行者123 更新时间:2023-12-01 22:47:20 25 4
gpt4 key购买 nike

我有一个用于日志记录的 Spring AOP 方面,其中可以通过添加注释来包含用于日志记录的方法,如下所示:

@AspectLogging("do something")
public void doSomething() {
...
}

我一直在 Spring beans 上使用它,并且运行得很好。现在,我想在 REST 服务上使用它,但遇到了一些问题。所以,我有:

@Path("/path")
@Service
public class MyRestService {
@Inject
private Something something;

@GET
@AspectLogging("get some stuff")
public Response getSomeStuff() {
...
}
}

这个设置工作得很好。我尝试添加日志记录的休息服务现在有一个接口(interface),但不知怎的,这把事情弄乱了。一旦我将 @AspectLogging 注释添加到其中一个方法,bean 中就不会注入(inject)任何依赖项,而且方面也会被更新调用!

我尝试向可用的 REST 服务添加一个接口(interface),但出现了相同的错误。

接口(interface)怎么会导致这种类型的问题呢?方面记录器适用于在其他地方具有接口(interface)的类,似乎只有当它是 REST 服务时才会出现问题..

最佳答案

引用下面的 Spring 文档(第 2 段)-

To enable AspectJ annotation support in the Spring IoC container, you only have to define an empty XML element aop:aspectj-autoproxy in your bean configuration file. Then, Spring will automatically create proxies for any of your beans that are matched by your AspectJ aspects.

For cases in which interfaces are not available or not used in an application’s design, it’s possible to create proxies by relying on CGLIB. To enable CGLIB, you need to set the attribute proxy-targetclass= true in aop:aspectj-autoproxy.

如果您的类实现了接口(interface),则将使用 JDK 动态代理。但是,如果您的类没有实现任何接口(interface),那么将创建一个 CGLIB 代理。您可以实现此@EnableAspectJAutoProxy。这是示例

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

@Bean
public LoggingAspect logingAspect(){
return new LoggingAspect();
}
}



@Component
@Aspect
public class LoggingAspect {

...
...

}

关于java - Rest + Spring AOP + 接口(interface)不注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25141487/

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