Spring代理的两种方式
一、使用配置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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.spring">
<bean id="myPlus" class="com.spring.plus.MyPlus"></bean>
<aop:config>
<aop:aspect ref="myPlus"><!--切面:加强类myPlus-->
<aop:before method="plus" pointcut="execution(public void com.spring.dao.impl.AgentDaoImpl.levelUp(..))"/><!--加强方法puls即表示在调用 AgentDaoImpl 类 中的 levelUp()方法之前会先调用plus方法-->
</aop:aspect>
</aop:config>
</beans>
二、使用注解实现代理
1、在使用注解之前要在xml配置文档中实现自动代理
<aop:aspectj-autoproxy></aop:aspectj-autoproxy><!--自动代理标签-->
在切面即加强类中使用@Aspect注解
如:
package com.spring.plus;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect//使之成为切面
public class MyPlus {
@Before("execution(void com.spring.dao.impl.AgentDaoImpl.levelUp())")//切点:前置通知,在执行levelUp之前执行puls()方法
public void plus(){
System.out.println("一刀999,装备回收秒到账!");
}
}
AgentDao类
package com.spring.dao.impl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.spring.dao.AgentDao;
import com.spring.plus.MyPlus;
@Component("agentDao")
public class AgentDaoImpl implements AgentDao {
@Override
public void levelUp() throws Exception {
System.out.println("this is AgentDao implement class!");
}
}
Test 测试类
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyPlus p=(MyPlus) context.getBean("myPlus");
try {
AgentDao agentDao=(AgentDao) context.getBean("agentDao");
agentDao.levelUp();
} catch (Exception e) {
e.printStackTrace();
}
}
输出结果:
一刀999,装备回收秒到账!
this is AgentDao implement class!