当我使用spring-aspect时 - bean myClass 不会注入。为什么可能,以及如何在这种情况下启用注射呢?
如果 aop:config 在XML中被注释掉,则输出为:
myClass from constructor: MyClass{myInt=3333}
myClass from main: MyClass{myInt=3333}
app logEvent
如果 aop:config 在XML中被注释掉 NOT ,则输出为:
myClass from constructor: MyClass{myInt=3333}
myClass from main: null
LOG: BEFORE : App logEvent
app logEvent
App.java
public class App {
MyClass myClass;
public static void main(String[] args) {
ApplicationContext ctx;
ctx = new ClassPathXmlApplicationContext("conf.xml");
App app = (App) ctx.getBean("app");
System.out.println("myClass from main: " + app.myClass);
app.logEvent();
}
public App(MyClass myClass) {
this.myClass = myClass;
System.out.println("myClass from constructor: " + this.myClass);
}
public void logEvent(){
System.out.println("app logEvent");
}
}
MyClass.java
public class MyClass {
int myInt=6789;
public int getMyInt() {return myInt;}
public void setMyInt(int myInt) {this.myInt = myInt;}
@Override
public String toString() {return "MyClass{myInt=" + myInt +'}'; }
}
MyAspect.java
public class MyAspect {
public void logBefore(JoinPoint joinPoint) {
System.out.println("LOG: BEFORE : " +
joinPoint.getTarget()
.getClass().getSimpleName() + " " +
joinPoint.getSignature()
.getName()
);
}
}
conf.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="app" class="com.geka.spring2.App" c:myClass-ref="myClass"/>
<bean id="myClass" class="com.geka.spring2.MyClass" p:myInt="3333" />
<bean id="aBean" class="com.geka.spring2.MyAspect" />
<aop:aspectj-autoproxy />
<aop:config>
<aop:aspect id="myAspect" ref="aBean">
<aop:pointcut id="cLogg" expression="execution(* *.logEvent(..))"/>
<aop:before pointcut-ref="cLogg" method="logBefore"/>
</aop:aspect>
</aop:config>
答案 0 :(得分:0)
MyClass
似乎不是@Component,因此可能无法在ComponentScan中找到
答案 1 :(得分:0)
一切都变得更简单了。 Spring AOP代理不代理字段