spring 中事件处理用例

使用spring 事件非常简单

首先继承 ApplicationEvent

public class SampleEvent extends ApplicationEvent {
    private String otherProperty;


    public String getOtherProperty() {
        return otherProperty;
    }

    public void setOtherProperty(String otherProperty) {
        this.otherProperty = otherProperty;
    }

    public SampleEvent(Object source) {
        super(source);    //To change body of overridden methods use File | Settings | File Templates.
    }
}

然后做 SampleEventListener 实现 ApplicationListener

public class SampleEventListener implements ApplicationListener {
    protected Log log = LogFactory.getLog(this.getClass());

    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof SampleEvent) {
            SampleEvent se = (SampleEvent) event;
            System.out.println(se.getOtherProperty());
            log.debug(se.getOtherProperty());

        }
    }
}

然后实现 SampleEventPublisher 发布 事件

public class SampleEventPublisher implements ApplicationContextAware {
    private ApplicationContext ctx;


    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.ctx = applicationContext;

    }

    public void publishAction(String otherProperty) {
        SampleEvent se = new SampleEvent(this);
        se.setOtherProperty(otherProperty);

        ctx.publishEvent(se);

    }

}

applicationContext 配置

<beans></beans>
    <bean class="com.test.spring.applicationEvent.SampleEventListener"></bean>
    <bean class="com.test.spring.applicationEvent.SampleEventPublisher" id="samplePublisher"></bean>

 

做 Test 测试

 

public class SampleEventTest extends TestCase {
    protected void setUp() throws Exception {
        super.setUp();    //To change body of overridden methods use File | Settings | File Templates.
    }

    public void testSampleEventPublish() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        SampleEventPublisher sep = (SampleEventPublisher) ctx.getBean("samplePublisher");
        sep.publishAction("this is sample property");


    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值