Spring之AOP入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011301372/article/details/81486998

AspectJ的xml方式完成AOP开发

步骤一:创建Javaweb项目,引入具体的开发的jar包

  • 先引入Spring框架开发的基本开发包
  • 再引入Spring框架的AOP的开发包
    • Spring的传统AOP的开发的包
      • Spring-aop-4.2.4RELEASE.jar
      • com.springsource.org.aopalliance-1.0.0.jar
    • aspectJ的开发包
      • com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
      • spring-aspects-4.2.4.RELEASE.jar

步骤二:创建Spring的配置文件,引入具体的AOP的schema约束

步骤三:创建包结构,编写具体的接口和实现类

  • com.xd.demo1
    • CustomerDao——接口
    • CustomerDaoImpl——实现类

步骤四:将目标类配置到Spring中

<bean id = "cutomerDao" class="com.xd.demo2.CustomerDaoImpl"/>

步骤五:定义切面类

public class MyAspectXml{
    //定义通知
    public void log(){
        System.out.println("记录日志。。。");
    }
}

步骤六:在配置文件中定义切面类

<bean id="myAspectXml" class="com.xd.demo2.MyAspectXml"/>

步骤七:在配置文件中完成aop的配置

<!--编写切面类配置-->
    <bean id="myAspectXml" class="com.xd.demo2.MyAspectXml"/>
    <!--配置AOP-->
    <aop:config>
        <!--配置切面类:切入点+通知-->
        <aop:aspect ref="myAspectXml">
            <!--配置前置通知,save方法执行之前,增强的方法会执行-->
            <!--切入点的表达式:execution(public void com.xd.demo2.CustomerDaoImpl.save() )-->
            <aop:before method="log" pointcut="execution(public void com.xd.demo2.CustomerDaoImpl.save())"/>
        </aop:aspect>
    </aop:config>

步骤八:完成测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo3 {
    @Resource(name="dao")
    private CustomerDao customerDao;
    @Test
    public void run1(){
        customerDao.save();
        customerDao.update();
    }

}

猜你喜欢

转载自blog.csdn.net/u011301372/article/details/81486998