我是AOP的新手,慢慢阅读并学习SpringAOP和AspectJ。
我遇到了一个意想不到的例子,一个不是作为bean创建但是由作为bean创建的工厂创建的对象正在代理我的方面,而我期待的只是那些对象。由Spring创建,用SpringAOP中的适用方面代理。
Spring如何知道代理一个由spring注册的工厂创建的对象?意思是spring怎么会知道我自己的工厂实际上是一个工厂而DogShelter.getAngryDog()
返回的对象是一个新的对象需要用代理包装而不是之前已经包装的现有AngryDog
与方面代理?
以下是代码:
对象:
public class AngryDog extends Dog {
@Override
public void play() {
System.out.println("AngryDog->play()");
bark();
bite();
}
@Override
public void bark() {
System.out.println("AngryDog->bark()");
}
@Override
public void bite() {
System.out.println("AngryDog->bite()");
}
}
厂:
public class DogShelter {
public AngryDog getAngryDog(){
return new AngryDog();
}
}
方面:
@Aspect
public class BeforeAllDogMethodsAspect {
@Before("execution(* com.demos.dogs.*.*(..)))")
public void doAccessCheck() {
System.out.println("SpringAOP aspect called!");
}
}
Spring Config:
/** DogConfig spring configuration */
@EnableAspectJAutoProxy
@Configuration
public class DogConfig {
@Bean
public AngryDog dog() {
return new AngryDog();
}
@Bean
public DogShelter dogShelter(){
return new DogShelter();
}
@Bean
public BeforeAllDogMethodsAspect beforeAngryDogBitesExample(){
return new BeforeAllDogMethodsAspect();
}
}
调用:
foo(){
System.out.println("----------------");
System.out.println("Getting a dog from locally created dog shelter. And playing with it");
DogShelter locallyCreatedDogShelter = new DogShelter();
AngryDog dogFromLocalShelter = locallyCreatedDogShelter.getAngryDog();
dogFromLocalShelter.play();
System.out.println("----------------");
System.out.println("Getting a dog from autowired dog shelter. And playing with it");
AngryDog dogFromAutoWiredDogShelter = autowiredDogShelter.getAngryDog();
dogFromAutoWiredDogShelter.play();
}
输出:
----------------
Getting a dog from locally created dog shelter. And playing with it
AngryDog->play()
AngryDog->bark()
AngryDog->bite()
----------------
Getting a dog from autowired dog shelter. And playing with it
SpringAOP aspect called!
AngryDog->play()
AngryDog->bark()
AngryDog->bite()
答案 0 :(得分:2)
您应该在方面中显示方法名称。否则,您不知道截获哪种方法。
关于你的问题:可能截获的是getAngryDog()方法而不是play()方法。