Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未为bean的set方法处理切入点内的SPRING AOP_Spring_Spring Aop - Fatal编程技术网

未为bean的set方法处理切入点内的SPRING AOP

未为bean的set方法处理切入点内的SPRING AOP,spring,spring-aop,Spring,Spring Aop,简言之: a) spring.xml <aop:aspectj-autoproxy /> <bean id="circle" class="org.tutorial.spring.model.Circle"> <property name="name" value="Circle name" /> </bean> <bean id="triangle" class="org.tutorial.spring.model.Triang

简言之:

a) spring.xml

<aop:aspectj-autoproxy />

<bean id="circle" class="org.tutorial.spring.model.Circle">
    <property name="name" value="Circle name" />
</bean>

<bean id="triangle" class="org.tutorial.spring.model.Triangle">
    <property name="name" value="Triangle name" />
</bean>

<bean id="shapeService" class="org.tutorial.spring.service.ShapeService" autowire="byName" />

<bean class=" org.tutorial.spring.aspect.LoggingAspect" />
c) 圆类

package org.tutorial.spring.model;

public class Circle {

private String name;

public String getName() {
    System.out.println("Circle getName");
    return name;
}

public void setName(String name) {
    System.out.println("Circle setName");
    this.name = name;
}

}
d) LoggingAspect类

@Aspect
public class LoggingAspect {

@Before("allCircleMethods()")
public void securityAdvice() {
    System.out.println("Security Advice is executed!");
}

@Pointcut("within(org.tutorial.spring.model.Circle)")
public void allCircleMethods() {
}

}
e) ShapeAOP类(要运行的主类)

输出:

圈集合名
执行安全建议
圈选getName
圈名

请注意,在Circle bean实例化期间,在“Circle setName”之前没有“执行安全建议”的输出


为什么for Circle类中的切入点没有应用到Circle setName方法?

用户pap在评论部分回答了我的问题,似乎切入点在bean初始化之后才设置。哪种是有意义的。将建议应用于尚未完全构建的bean(即处于不确定状态)会引发各种潜在问题。您是否尝试过显式调用您的
setName()
方法(例如在
main
中)来验证是否应用了建议?@pap您是对的。在bean实例化期间应用该建议没有意义。我测试了它,它证实了你的发现。谢谢
@Aspect
public class LoggingAspect {

@Before("allCircleMethods()")
public void securityAdvice() {
    System.out.println("Security Advice is executed!");
}

@Pointcut("within(org.tutorial.spring.model.Circle)")
public void allCircleMethods() {
}

}
public class ShapeAOP {

public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
    ShapeService shapeService = ctx.getBean("shapeService", ShapeService.class);
    System.out.println(shapeService.getCircle().getName());
}

}