发表于: 2017-12-03 19:42:15

1 725


今天完成的内容:

(1)aop小实例:

主要是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:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

   <bean id="helloWorldImpl1" class="imp.HelloWorldImpl1" />
   <bean id="helloWorldImpl2" class="imp.HelloWorldImpl2" />
   <bean id="timeHandler" class="fun.TimeHandler" />

   <aop:config>
   <aop:aspect id="time" ref="timeHandler">
       <aop:pointcut id="addAllMethod" expression="execution(* fun.HelloWorld.*(..))" />
       <aop:before method="printTime" pointcut-ref="addAllMethod" />
       <aop:after method="printTime" pointcut-ref="addAllMethod" />
   </aop:aspect>
</aop:config>

</beans>

通过配置文件在HelloWorld前后加printTime的方法

public void printTime() {


System.out.println("CurrentTime = " + System.currentTimeMillis());
}

运行类中通过bean创建对象:

public static void main(String[] args) {

ApplicationContext ctx = new ClassPathXmlApplicationContext("aop.xml");

   HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1");
   HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2");

   hw1.printHelloWorld();
   System.out.println();

   hw1.doPrint();
   System.out.println();

   hw2.printHelloWorld();
   System.out.println();

   hw2.doPrint();
}

输出:

我的理解是,aop可横向插入功能组件,比如打印时间、打印日志等,这样就不用在原代码中重复的加这些功能代码。

小知识:

eturn语句有两种形式:

return;

return expression;

不带返回值的return语句只能用于返回类型为void的函数。在返回类型为void的函数中,return返回语句不是必需的,隐式的return发生在函数的最后一个语句完成时。

一般情况下,返回类型是void的函数使用return语句是为了引起函数的强制结束,这种return的用法类似于循环结构中的break语句

System.out.print(); 输出一行空格,即换行。

明天的计划:找漏,补。

遇到的问题:xml路径问题

收获:对aop更加了解了。


返回列表 返回列表
评论

    分享到