SpringAop之注解

使用注解进行简化aop的配置


切点是run方法

Car.java

package com.lubby.bean;

import org.springframework.stereotype.Component;

@Component("car")
public class Car {

	public void run(){
		System.out.println("Car is running....");
	}

}


切面

DoSomething.java

package com.lubby.bean;


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


@Component
@Aspect
public class DoSomething {
	@Pointcut("execution(* com.lubby.bean.Car.run(..))")
	private void run() {	}
	@Before("run()")
	public void prepare() {
		System.out.println("checking the car");
	}
	@After("run()")
	public void stop() {
		System.out.println("stopping the car to stoping place....");
	}
	@AfterThrowing("run()")
	public void fix() {
		System.out.println("fixing thr car....");
	}
}

test.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	default-lazy-init="true"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    ">

	<!-- 自动检测并注册为spring中的bean+启用注解 -->
	<context:component-scan base-package="com.lubby.bean"></context:component-scan>
	<aop:config>
		<aop:aspect ref="something">
			<aop:pointcut expression="execution(* com.lubby.bean.Student.readBook(..))"
				id="readBook" />
		</aop:aspect>
	</aop:config>
 <aop:aspectj-autoproxy/>   ---自动代理Bean
</beans>

test.xml

public class Test {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("com/lubby/bean/test.xml");
		Car car = (Car) ctx.getBean("car");
		car.run();
	}
}

结果

checking the car
Car is running....
stopping the car to stoping place....


SpringAop之注解,布布扣,bubuko.com

SpringAop之注解

上一篇:【C语言天天练(七)】回调函数


下一篇:java maven quartz exampe 实战攻略