spring aop的最简单的例子

下面先写一个简单的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值