通过代码入门Spring②何为AOP

TestApp.java

package cn.podger.spring.demo2;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * 
 * 在上一案例,应该对spring的ioc功能有一定的了解 这个项目的代码为展示spring的AOP功能. AOP
 * 全称解析为面向切面编程,它的实现原理就是通过代理去试试.
 * 因此spring使用策略模式,提供2种不同的实现方式,一种是基于CGLIB.一种是JDK的动态代理的方式.
 * 这2种的实现区别是:cglib是基于类,而JDK的动态代理通过去实现InvocationHandler接口去实现, 代理的类都需要接口.
 * 对于这2种实现方式,这里就不详细说明了.相应的文章颇多.
 */
public class TestApp {

	private static ApplicationContext context = null;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		context = new FileSystemXmlApplicationContext("applicationContext.xml");
	}

	@Test
	public void testMethod() throws Exception {
		UserService us = (UserService) context.getBean(UserService.class);
		us.findUserById(100L);
	}

}

AspectConfig .java

package cn.podger.spring.demo2;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AspectConfig {

	@Pointcut("execution(* cn.podger.spring.demo2.UserService.*(..))")
	public void aspect() {
	}

	@Before("aspect()")
	public void before(JoinPoint joinPoint) {
		System.out.println("执行前...");
	}

	@After("aspect()")
	public void after(JoinPoint joinPoint) {
		System.out.println("执行后...");
	}

}

UserService .java

package cn.podger.spring.demo2;

import org.springframework.stereotype.Service;

@Service
public class UserService {

	public void findUserById(Long id) {
		System.out.println("根据ID查询用户...");
	}

}

applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan base-package="cn.podger.spring.demo2" />
	<aop:aspectj-autoproxy />
</beans>

结果
这里写图片描述
项目下载http://download.csdn.net/detail/bojie5744/9546346

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜欢吃一口烤肉的啵啵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值