先建接口
package myaop;
public interface HelloWorld {
void printHelloWorld();
void doPrint();
}
修饰接口
package myaop;
public class HelloWorldImpl1 implements HelloWorld {
@Override
public void printHelloWorld() {
// TODO Auto-generated method stub
System.out.println("hello world");
}
@Override
public void doPrint() {
// TODO Auto-generated method stub
System.out.println("doprint");
}
}
想要织入的类
package myaop;
public class printtime {
private void syso() {
// TODO Auto-generated method stub
System.out.println("打印時間a");
}
private void logging() {
// TODO Auto-generated method stub
System.out.println("日志处理");
}
}
配置文件
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<bean id="helloworld" class="myaop.HelloWorldImpl1">
</bean>
<bean id="printtime" class="myaop.printtime"></bean>
<aop:config>
<aop:aspect id="dotime" ref="printtime">
<aop:pointcut id="adddoMethod"
expression="execution(* myaop.HelloWorldImpl1.do*(..))" />
<aop:before method="syso" pointcut-ref="adddoMethod" />
<aop:after method="syso" pointcut-ref="adddoMethod" />
</aop:aspect>
<aop:aspect id="printtime" ref="printtime">
<aop:pointcut id="addprintMethod"
expression="execution(* myaop.HelloWorldImpl1.print*(..))" />
<aop:before method="logging" pointcut-ref="addprintMethod" />
</aop:aspect>
</aop:config>
</beans>
测试类
package myaop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class a {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld hw1 = (HelloWorld)ctx.getBean("helloworld");
hw1.printHelloWorld();
hw1.doPrint();
}
}