18、spring AOP自动创建代理bean


18、spring AOP自动创建代理bean

自动创建了代理bean的作用就在于,简化代理bean的手动创建,免得代理bean在配置文件中堆积如山。

这里使用上一个例子的demo17、spring AOP通知——Pointcut、Advisor
创建代理bean的步骤如下:

第一步

修改bean配置文件

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="helloWorldService" class="com.main.AOP.autoCreateAdvice.HelloWorld">
        <property name="name" value="jack"/>
        <property name="type" value="user"/>
    </bean>

    <!-- 环绕通知的bean -->
    <bean id="adviceAround" class="com.main.AOP.autoCreateAdvice.AdviceAroundService"></bean>

    <!-- 声明切入点和代理的关系的bean -->
    <bean id="helloWorldAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
        <property name="mappedName" value="printName" />
        <property name="advice" ref="adviceAround" />
    </bean>

    <bean  class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
            <list>
                <value>*Service</value>
            </list>
        </property>
        <property name="interceptorNames">
            <list>
                <value>helloWorldAdvisor</value>
            </list>
        </property>
    </bean>
</beans>

这时可以用helloWorldService的原始bean名来获取,就像这样:

HelloWorld helloworld = (HelloWorld)context.getBean("helloWorldService");

自动创建Pointcut和Advisor

<bean id="helloWorldService" class="com.main.AOP.autoCreateAdvice.HelloWorld">
        <property name="name" value="jack" />
        <property name="type" value="user" />
    </bean>

    <bean id="adviceAround" class="com.main.AOP.autoCreateAdvice.AdviceAroundService" />

    <bean id="helloWorldAdvisor"
 class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
        <property name="mappedName" value="printName" />
        <property name="advice" ref="adviceAround" />
    </bean>

       <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告