spring18-3: 工厂bean代理-半自动
生活随笔
收集整理的這篇文章主要介紹了
spring18-3: 工厂bean代理-半自动
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?切面類
import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation;public class MyAspect implements MethodInterceptor{@Overridepublic Object invoke(MethodInvocation mi) throws Throwable {System.out.println("前");// 手動執(zhí)行目標方法Object obj = mi.proceed();System.out.println("后");return obj;} }接口?
public interface UserService {void addUser();void updateUser(); }?實現(xiàn)類
public class UserServiceImpl implements UserService {@Overridepublic void addUser() {System.out.println("bean adduser...");}@Overridepublic void updateUser() {System.out.println("bean updateUser...");} }配置文件?
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"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"><!-- 1.創(chuàng)建目標類 --><bean id="userService" class="com.atchina.b_factory_bean.UserServiceImpl"/><!-- 2.創(chuàng)建切面類 --><bean id="myAspect" class="com.atchina.b_factory_bean.MyAspect"/><!-- 3.創(chuàng)建代理類 ProxyFactoryBean用于創(chuàng)建工廠bean,生成特殊代理對象interfaces: 確定接口target: 確定目標類interceptorNames: 通知, 切面類的名稱, 類型是string[], --><bean id="proxyService" class="org.springframework.aop.framework.ProxyFactoryBean"><property name="interfaces" value="com.atchina.b_factory_bean.UserService"></property><property name="target" ref="userService"></property><property name="interceptorNames" value="myAspect"></property></bean> </beans>?測試類:
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestFactoryBean {@Testpublic void test(){String xmlPath = "com/atchina/b_factory_bean/applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(xmlPath);UserService userService = (UserService)ac.getBean("proxyService");userService.addUser();} }?
總結(jié)
以上是生活随笔為你收集整理的spring18-3: 工厂bean代理-半自动的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring18-2:采用cglib字节
- 下一篇: spring18-4: spring a