暑期ssh框架spring学习笔记四

前面两篇博客已经详细记录了面向切向编程的第一种实现方法,即手动代理,包含jdk动态代理和cglib代理。这里将要使用第三种方法,即声明式工厂Bean。

假设我们使用的目标类并不变化,仍然是原先的代码,换句话讲,我们的“面包”并没有改变,改变的是我们组织“食材”的方式以及“烹饪”的方法。下面的代码与以往不同的是我们将“食材”的“模子”和将其加入到面包中两个步骤结合成一个步骤

package cn.itcast.factorybean;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
//需要实现接口,确定哪个通知,以及告诉spring应该执行哪个方法
public class MyAspect implements MethodInterceptor{
      @Override
      public Object invoke(MethodInvocation mi)throws Throwable{
     System.out.println("方法执行之前");
     //执行目标方法
     Object obj=mi.proceed();
     System.out.println("方法执行之后");
   }
}

上面的代码虽然已经将“面包”和食材放在了面包中,但是仅仅凭此还远远不够,我们还需要在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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!-- 1、设置目标类 -->
     <bean id="userDao" class="cn.itcast.dao.UserDaoImpl"></bean>
     <!-- 2、设置advice-->
     <bean id="myAspect" class="cn.itcast.factorybean,MyAspect"></bean>
     <!-- 3、生成代理对象,将上面配置的目标对象和advice进行组合-->
     <bean id="userDaoProxy" class="org.springframework.ProxyFactoryBean">
     <!-- 3.1代理实现的接口,value的值是上面的接口的id-->
     <property name="interfaces" value="cn.itcast.dao.UserDao"><property>
     <!--3.2目标,ref的值是上面接口的具体实现类,及目标类的的id-->
     <property name="target" ref="userdao"></property>
      <!-- 3.3用通知增强目标,value的值是上面配置切面类的id-->
      <property name="interceptorNames" value="myAspect"></property>
      <!-- 3.4配置代理的生成方式,true:使用cglib,false:使用jdk动态代理-->
     <property name="proxyTargetClass" value="true"></property>
</bean>
</beans>

到此为止,已经将面包切好,并且已经成功将食材放入到面包的切口中

下面我们将“烹饪”好的面包取出,注意这里由于我们“烹饪”面包的方式有所不同(我们采用xml文件配置),所以取出”烹饪好的面包“的方式也有所不同,反映在代码中的主要不同是需要加载xml配置文件:

package cn.itcast.factorybean;
 import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.dao.UserDao;

public class TestFactoryBean{
   @Test
   public void demo01(){
       String xmlPath="cn/itcast/factorybean/applicationContext.xml";
       ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
       //1、从spring获得容器
       UserDao userDao=(UserDao)applicationContext.getBean("userDaoProxy");
      }
      //执行方法,确定要在面包的哪个位置切开面包
      userDao.save();
      userDao.update();
      userDao.delete();
      userDao.find();
}

执行后的结果如下所示:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值