spring aop的最简单的例子
程序员文章站
2022-04-13 08:47:52
...
下面先写一个简单的spring aop例子
package com.eroadsf.springdemo.aop;
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 AspectJTest {
@Pointcut("execution(* *.say(..))")
public void say(){
}
@Before("say()")
public void beforeSay(){
System.out.println("beforeSay");
}
@After("say()")
public void afterSay(){
System.out.println("afterSay");
}
}
package com.eroadsf.springdemo;
import java.util.Date;
public class ServiceA {
private Date date;
private String name;
// private ServiceB serviceB;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// public ServiceB getServiceB() {
// return serviceB;
// }
//
// public void setServiceB(ServiceB serviceB) {
// this.serviceB = serviceB;
// }
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void say(){
System.out.println("输出:"+this.name);
}
}
<?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-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<bean id="serviceA" class="com.eroadsf.springdemo.ServiceA" scope="singleton">
<property name="name" value="何"></property>
</bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean class="com.eroadsf.springdemo.aop.AspectJTest"></bean>
</beans>
package com.eroadsf.springdemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试类
* @author hepei
* @date 2017年9月24日 下午11:37:43
*/
public class Test {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-context.xml");
ServiceA serviceA=(ServiceA) ctx.getBean("serviceA");
serviceA.say();
}
}
最后的打印结果:
beforeSay
输出:何
afterSay
上一篇: 最简单的struts完整例子
下一篇: SaltStack说明文档