为什么在建议之前在方法调用之前进行打印

时间:2018-04-15 14:26:19

标签: java annotations aop spring-aop aspect

MY 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>

Student.java

package 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;



}

Logging.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());

    }
}

输出:

在建议之前打电话给 建议后称为 Suraj Kudale
在建议之前称为 建议后称为 27

应该是:
在建议之前称为 Suraj Kudale
建议后称为 在建议之前称为 27个
建议后叫

1 个答案:

答案 0 :(得分:0)

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