您的位置:首页 > 编程语言 > Java开发

Spring Framework(1):Bean的自动装配检测 & AOP简述

2015-05-07 19:25 399 查看
Bean的自动装配

注解可以充分利用Java的反射机制获取类结构信息,从而有效减少配置工作;注解与java代码位于同一个文件,便于对变动的统一维护;

1) Spring容器默认禁用注解装配,因此使用注解装配之前需要在配置文件中显示打开注解装配:

<?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"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="
 http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
<context:annotation-config />

<bean id="audience" class="com.active.leo.helloworld.Audience" />

<bean id="instrumentAlist" class="com.active.leo.helloworld.InstrumentAlist" />

<bean id="instrument2" class="com.active.leo.helloworld.InstrumentImpl2"/>

<aop:config>

<aop:aspect ref="audience">

<aop:pointcut id="performance"

expression="execution(* com.active.leo.helloworld.Performer.perform(..))" />

<aop:before pointcut-ref="performance" method="takeSeats" />

<aop:before pointcut-ref="performance" method="turnOffCellPhones" />

<aop:after-returning pointcut-ref="performance" method="applaud" />

<aop:after-throwing  pointcut-ref="performance" method="demandRefund" />

</aop:aspect>

</aop:config>

</beans>


View Code
#1<aop:aspct表示定义一个切面,并且与名为audience的bean关联;

#2<aop:pointcut>表示定义一个名为performance的切点,并与调用perform方法触发绑定;

#3<aop:before>表示定义调用perform方法触发之前的动作;

#4<aop:after-returning>表示定义调用perform方法触发正常结束之后的动作;

#5<aop:after-throwing>表示定义调用perform方法抛出异常后的动作;

#6<aop:around>合并before和after-returning,PreceedingJoinPoint.proceed()为目标动作;

#7如果目标动作有参数,可以借助arg/arg-names在切面方法中获取;

3) Spring AOP也可以通过注解实现

#1首先要在配置文件中添加<aop:aspectj-autoproxy />;

#2然后通过@Aspect,@Pointcut,@Before,@AfterReturning,@Around等实现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: