gpt4 book ai didi

java - 为什么 Spring AOP 不在运行时编织外部 jar?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:25 24 4
gpt4 key购买 nike

我有一个基于 Spring 3 构建的 java 应用程序。这个项目有另一个 jar 作为依赖项。

此依赖项包含一个 @org.aspectj.lang.annotation.Aspect 类(比方说,com.aspectprovider.aspects.MyAspect)。有一个 @Before 建议从实现接口(interface) Foo 的类中编织一个方法。像这样的东西:

@Before("execution(* com.project.Foo.save(..))")

Foo 接口(interface)可以在“项目”中或在另一个 jar 中。对于此示例无关紧要。

我的项目包含实现 Foo 的类。当然,这些是我希望编织的类。

我的 Spring 应用程序上下文配置文件 (applicationContext.xml) 包含以下行:

<aop:aspectj-autoproxy />

我还将方面声明为 bean,并注入(inject)一些属性:

<bean id="myAspect" class="com.aspectprovider.aspects.MyAspect"
factory-method="aspectOf" >
<property name="someproperty" value="somevalue" />
</bean>

通过日志记录,我可以看到 MyAspect 已实例化并且属性已注入(inject)。但是方法save没有被拦截。这就是问题所在。

如果我将方面类从 jar 复制到具有 Spring 的应用程序,它就可以工作。当这些方面包含在外部 jar 中时,不会拦截方法 save。有什么线索吗?

编辑:我如何调用 Foo 的保存方法:

//in a JSF managed bean
@Inject
private Foo myFoo; //there's a implementation of Foo in a package that spring is looking at. So it is injected correctly.

public String someAction() {
myFoo.save("something"); //the @Before advice is only called if the class containing the aspect is not in an external jar
}


//in a class with a main method
void main(String[] ars) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//right after the previous line, I can see in the log that MyAspect is instantiated.
Foo myFoo = ac.getBean(Foo.class);
myFoo.save("something"); //the @Before advice is only called if the class containing the aspect is not in an external jar
}

基本上,我的 applicationContext.xml 有以下几行:

<context:annotation-config />
<context:component-scan base-package="com.project" />
<context:component-scan base-package="com.aspectprovider.aspects" />
<aop:aspectj-autoproxy />
<bean id="myAspect" class="com.aspectprovider.aspects.MyAspect" factory-method="aspectOf" >
<property name="someproperty" value="somevalue" />
</bean>

我不认为我需要放任何类似的东西

<context:component-scan  base-package="com.project">
<context:include-filter type="aspectj" expression="com.aspectprovider.aspects.*" />
</context:component-scan>

最佳答案

我也遇到了同样的问题。我用maven解决了这个打包问题。检查 aspectj-maven-plugin 和选项 weaveDependency

http://mojo.codehaus.org/aspectj-maven-plugin/weaveJars.html

关于java - 为什么 Spring AOP 不在运行时编织外部 jar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5956490/

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