我试图在java中创建一个简单的程序。
在我的程序中:
1) Person 类 - 带注释的方法
2)方面类。
现在我要做的是在设置人名之前,将一些数据打印到日志文件和控制台。
所以这就是我所做的:
人员类
package pack.bl;
import org.springframework.stereotype.Component;
import pack.aop.LogLevel;
import pack.aop.TestAnnotation;
@Component
public class Person {
private String name,dest;
public Person(String name,String dest)
{
this.setName(name);
this.setDest(dest);
}
public String getName() {
return name;
}
@TestAnnotation(value=LogLevel.INFO)
public void setName(String name) {
this.name = name;
System.out.println("Im " + this.toString() + " My name was changed to " + name);
}
public String getDest() {
return dest;
}
@TestAnnotation(value=LogLevel.INFO)
public void setDest(String dest) {
this.dest = dest;
}
@Override
public String toString()
{
return this.name + "\n";
}
public static void main(String[] args) {
Person p = new Person("Person1","Kripton");
p.setName("Person2");
}
}
方面类
package pack.aop;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.test.context.ContextConfiguration;
@Aspect
@ContextConfiguration(locations = {
"applicationContext.xml"})
public class BeforeAdvice {
private Log logger = LogFactory.getLog("Logger");
@Before("@annotation(testAnnotation)")
public void myBeforeLogger(JoinPoint joinPoint,TestAnnotation testAnnotation)
{
System.out.println("Okay - we're in the before handler...");
System.out.println("The test annotation value is: " + testAnnotation.value());
Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String stuff = signature.toString();
String arguments = Arrays.toString(joinPoint.getArgs());
logger.info("Write something in the log... We are just about to call method: "
+ methodName + " with arguments " + arguments + "\nand the full toString: "
+ stuff);
}
}
ApplicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<aop:aspectj-autoproxy/>
<context:component-scan base-package="pack.bl.Person"/>
*注意: LogLevel是一个枚举。所以它需要像这样工作,当我运行程序并设置人名时,首先需要转到 Aspect 类中的 'BeforeAdvice'(因为 setName,用@testAnnotation注释)方法,然后执行这个方法..之后需要回到setName方法并设置人名。*
还有一件事,testAnnotation 是我创建的 Annotation