实例演练
- 目标类:
package Explan;
import org.springframework.stereotype.Component;
@Component(value = "target")//target相当于id
public class Target2 {
public void method1() {
System.out.println("运行中。。。。");
}
}
- 通知类:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("advice")//advice相当于id
@Aspect//表明切面
public class Advice2 {
//第一个*表示返回任意类型,第二个"*.."表示所有包,//后面就是所有类下的这个方法
@Before(value = "execution(* *..*.method1())")
public void before() {
System.out.println("通知通知,将要启动方法~");
}
}
- 配置文件,config.xml:
<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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="Explan"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
4.测试类:
package Explan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ManagerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx=new ClassPathXmlApplicationContext("config.xml");
Target2 ta=(Target2)ctx.getBean("target");
ta.method1();
}
}
At lasr ,运行图:

+++++++++++++++++++++++++我是分割线+++++++++++++++++++++++++++++++++++
这些都是我自学过程中自己编写的例子,带着自己的理解,可能不是十分的标准和清晰,有错或者意见阔以私信我,一起学习互励共勉