Spring Core 官方文档阅读笔记(十)

Advisor是Advice和Pointcut组成的独立单元,可以传给proxy factory对象。

代码:

/**
 * @author kuromaru
 */
public interface MyInterface {

    void sayHello();

    void sayBye();
}
/**
 * @Author: kuromaru
 * @Date: Created in 15:54 2019/4/15
 * @Description:
 * @modified:
 */
public class MyInterfaceImpl implements MyInterface {
    @Override
    public void sayHello() {
        System.out.println("Hello everyone");
    }

    @Override
    public void sayBye() {
        System.out.println("Bye bye~");
    }
}
/**
 * @Author: kuromaru
 * @Date: Created in 15:55 2019/4/15
 * @Description:
 * @modified:
 */
public class MyAfterAdvice implements AfterReturningAdvice{

    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("stupid");
    }
}
/**
 * @Author: kuromaru
 * @Date: Created in 15:56 2019/4/15
 * @Description:
 * @modified:
 */
@Configuration
public class MyConfig {

    @Bean
    public MyAfterAdvice myAfterAdvice() {
        return new MyAfterAdvice();
    }

    @Bean("myTarget")
    public MyInterface myInterface() {
        return new MyInterfaceImpl();
    }

    @Bean("myProxy")
    public ProxyFactoryBean proxyFactoryBean() {
        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
        proxyFactoryBean.setTargetName("myTarget");
        proxyFactoryBean.setInterceptorNames("myAdvisor");
        return proxyFactoryBean;
    }

    @Bean("myAdvisor")
    public NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor() {
        NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor = new NameMatchMethodPointcutAdvisor();
        nameMatchMethodPointcutAdvisor.setAdvice(myAfterAdvice());
        nameMatchMethodPointcutAdvisor.setMappedName("sayBye");
        return nameMatchMethodPointcutAdvisor;
    }
}
/**
 * @Author: kuromaru
 * @Date: Created in 16:10 2019/4/15
 * @Description:
 * @modified:
 */
public class Client {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(MyConfig.class);
        MyInterface myInterface = (MyInterface) acac.getBean("myProxy");
        myInterface.sayHello();
        myInterface.sayBye();
    }
}

输出结果:

四月 15, 2019 5:56:56 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5387f9e0: startup date [Mon Apr 15 17:56:56 CST 2019]; root of context hierarchy
Hello everyone
Bye bye~
stupid

posted @ 2020-05-22 09:44  kuromaru  阅读(116)  评论(0)    收藏  举报