gpt4 book ai didi

java - 为什么 After Advice 在方法调用之前得到打印

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:32 26 4
gpt4 key购买 nike

我的 Spring AOP 程序未按预期运行。我在下面创建了简单的AOP注释程序,但输出不是我想象的。

节目:

Beans.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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<aop:aspectj-autoproxy/>


<bean id="student" class="com.surajhome.practice.spring.Student" >
<property name="name" value="Suraj Kudale"></property>
<property name="age" value="27"></property>
</bean>

<bean id="logging" class="com.surajhome.practice.spring.Logging"></bean>


</beans>

学生.java

包 com.surajhome.practice.spring;

public class Student {

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
String name;
int age;



}

日志记录.Java

package com.surajhome.practice.spring;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class Logging {

@Pointcut("execution(* com.surajhome.practice.spring.*.*(..) )")
public void selectAll()
{

}
@After("selectAll()")
public void afterAdvice()
{
System.out.println("After Advice called");
}

@Before("selectAll()")
public void beforeAdvice()
{
System.out.println("Before Advice called");
}

public void afterReturningAdvice()
{
System.out.println("After Returning Advice called");
}

public void afterThrowingException()
{
System.out.println("After Exception Advice called");
}

}

MainApp.java

package com.surajhome.practice.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext appContext=new ClassPathXmlApplicationContext("Beans.xml");

Student std=(Student) appContext.getBean("student");


System.out.println(std.getName());
System.out.println(std.getAge());

}
}

输出:

调用建议之前
调用建议后
苏拉吉·库代尔
在调用建议之前
调用建议后
27

应该是:
在调用建议之前
苏拉吉·库代尔
调用建议后
在调用建议之前
27
调用建议后

最佳答案

想想当您调用 System.out.println(std.getName()); 时发生的流程,首先调用get name的@Before方法,然后get name返回一个值,然后调用@After,然后System.out.println获取字符串并打印它

关于java - 为什么 After Advice 在方法调用之前得到打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49843024/

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