超简单Spring入门 (二) Aspect-oriented Programming

 

除了Dependency Injection, Spring还能做什么呢?

回答是aspect-oriented programming。

当我们在写程序的时候,除了实现core logic之外,还有很多附加的功能。例如logging,transaction management and security。

经常发生的情况是程序中的多个component都需要类似服务,而我们不得不在每个component中重复类似的代码。

实际上这样做导致core logic中散布着不太相关的代码。而对于面向对象编程,最理想的情况是,一个类只需要关注自身的功能,而不需要再去操心如何记日志等其他事情。

下面把spring入门(一)文章中的例子再稍微变化一下:在执行run()前后,打印点别的东西。

 

<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:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<bean id="writer" class="org.lillian.Spring.Writer" />

<bean id="mySpringBeanWithDependency" class="org.lillian.Spring.MySpringBeanWithDependency">
<property name="writer" ref="writer" />
</bean>

<bean id="formatText" class="org.lillian.Spring.FormatText" /> //注册一个新的bean

<aop:config> //要使用aop,必须使用aop configuration namespace
 <aop:aspect ref="formatText">
  <aop:pointcut id="print" expression="execution(* *.run(..))"/> //设置一个pointcut,意思是任何对象运行run方法时,都是一个printcut。
  <aop:before pointcut-ref="print" method="formatBeforeWrite"/> //定义在pointcut前执行什么
  <aop:after pointcut-ref="print" method="formatAfterWrite"/> //定义在pointcut后执行什么
 </aop:aspect>
</aop:config>

</beans>

FormatText类 的内容:

public class FormatText {
 
 public void formatBeforeWrite(){
  System.out.println("Begin to print!");
 }
 public void formatAfterWrite(){
  System.out.println("End of the printing!");
 }

}

运行结果:

在程序代码中的任意地方运行任意对象的run方法时,前后都会被打印上面配置的"Begin to print!“和"End of the printing!"。

注意定义printcut时,在execution中使用的语法是:

The expression syntax is AspectJ’s pointcut expression language. 大家自己去学习吧。


由此可见,通过AOP,我们可以随意的在方法前后执行一些其他的功能。用aop来解决例如在代码中输出log这类的应用是不是太方便了呢?

最重要的是,无论是core class还是附加的class的代码都没有任何改变,他们之间的调用完全是靠配置文件实现的。

此外Spring还有一个重要功能:template。例如Spring的 SimpleJdbcTemplate。关于template,以后如果有机会再提。

好了,明白了Spring要干什么,大概怎么实现就算入门了~~~

进一步的学习,向大家推荐一本书:

Spring in action-- third edition

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值