SpringAOP注解的HelloWorld


该案例演示SpringAOP的注解方式的开发。大家可以和XML方式进行对比学习,《SpringIOC的HelloWorld》。

一、编写业务类

CustomerService:

package com.yiidian.service;
/**
 * @author http://www.yiidian.com
 *
 */
public interface CustomerService {

	public void save(String name);
	
	public void update();
}

CustomerServiceImpl:

package com.yiidian.service.impl;

import com.yiidian.service.CustomerService;
/**
 * 这个类在AOP属于目标对象(Target)
 * @author http://www.yiidian.com
 *
 */
public class CustomerServiceImpl implements CustomerService {

	@Override
	public void save(String name) {
		System.out.println("执行save方法,name为:"+name);
	}

	@Override
	public void update() {
		System.out.println("执行update方法");
	}

}

二、编写AOP注解的切面类

package com.yiidian.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;


/**
 * Spring的AOP的切面类
 * @author http://www.yiidian.com
 *
 */
@Aspect
public class MyAspect {

	@Before(value="execution(public * com.yiidian.service.impl.CustomerServiceImpl.*(..))")
	public void writeLog(){
		System.out.println("SpringAOP注解记录日志");
	}

}
@AspectJ使用了Java 5的注解,可以将切面声明为普通的Java类。@AspectJ样式在AspectJ 5发布的AspectJ project部分中被引入。Spring 2.0使用了和AspectJ 5一样的注解,并使用AspectJ来做切入点解析和匹配。但是,AOP在运行时仍旧是纯的Spring AOP,并不依赖于AspectJ的编译器或者织入器(weaver)。 

三、启用@AspectJ支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.xsd">

	<!-- 基于AspectJ的spring的AOP编写之XML方式 -->
	
	<!-- 1.创建目标对象 -->
	<bean id="customerService" class="com.yiidian.service.impl.CustomerServiceImpl"/>
	
	<!-- 2.创建切面类对象 -->
	<bean id="myAspect" class="com.yiidian.aspect.MyAspect"/>
	
	<!-- 开启SpringAOP注解功能 -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

四、编写测试类

package com.yiidian.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.yiidian.service.CustomerService;
/**
 * @author http://www.yiidian.com
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {

	@Resource
	private CustomerService customerService;
	
	@Test
	public void test1(){
		customerService.update();
	}
}

五、运行结果

 

源码下载:http://pan.baidu.com/s/1hsgqAJa