基于xml的注解配置
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启spring对aop的支持 -->
<aop:aspectj-autoproxy />
<!-- 配置对象 -->
<bean id="people" class="com.xu.springannotion.aopannotion.People"></bean>
<bean id="peopleplus"
class="com.xu.springannotion.aopannotion.PeoplePlus"></bean>
</beans>
people类(需要增强的类)
public class People {
public void sleep() {
System.out.println("睡觉啦");
}
}
peopleplus(增强类)
@Aspect
public class PeoplePlus {
@Before(value = "execution(* com.xu.springannotion.aopannotion.People.sleep(..))")
public void before() {
System.out.println("洗脸");
}
}
测试
public class Test {
@org.junit.Test
public void testName() throws Exception {
ApplicationContext context=new ClassPathXmlApplicationContext("com/xu/springannotion/Aopannotion.xml");
People people=(People) context.getBean("people");
people.sleep();
}
}
纯注解配置
people(要增强的类)
@Component
public class People {
public void sleep() {
System.out.println("睡觉啦!");
}
}
peopleplus(增强类)
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 PeoplePlus {
@Pointcut(value="execution(* com.xu.springannotion.allaopannotion.People.sleep(..))")
public void plus() {
}
@Before("plus()")
public void before() {
System.out.println("睡觉之前要刷牙洗脸!");
}
}
config类(容器类)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(basePackages = "com.xu.springannotion.allaopannotion")
@EnableAspectJAutoProxy
public class Config {
@Bean(name="peo")
public People getpeople() {
return new People();
}
}
test类
import static org.junit.Assert.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
@org.junit.Test
public void testName() throws Exception {
ApplicationContext context=new AnnotationConfigApplicationContext(com.xu.springannotion.allaopannotion.Config.class);
People people=(People) context.getBean("people");
people.sleep();
}
}