Spring的事务机制
---恢复内容开始---
内定的=>(只需要在xml 中添加一个bean)
在xml 中添加
<bean id="listener" class="com.test.事件机制.listener">
</bean>
测试
public void listenerTest(){
AbstractApplicationContext aContext=new ClassPathXmlApplicationContext("bean.xml");
aContext.refresh();
}
public class listener implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent arg0) {
// TODO Auto-generated method stub
if (arg0 instanceof ContextClosedEvent) {
System.out.println(arg0.getClass().getSimpleName()+"事实发生");
}
}
自定义事件==》
event:
public class myselfEvent extends ApplicationEvent{
String name;
public myselfEvent(Object source) {
super(source);
}
public myselfEvent(Object o,String name){
super(o);
this.name=name;
}
}
发布:
public class animal implements ApplicationContextAware{
private ApplicationContext ac;
private String sleepsString;
public String getSleepsString() {
ac.publishEvent(new myselfEvent(this, this.sleepsString));
return sleepsString;
}
public void setSleepsString(String sleepsString) {
this.sleepsString = sleepsString;
}
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.ac=arg0;
}
}
监听:
public class listener implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent arg0) {
// TODO Auto-generated method stub
if (arg0 instanceof myselfEvent) {
System.out.println(arg0.getClass().getSimpleName()+"事实发生");
}else{
System.out.println(arg0.getClass().getName()+"other");
}
}
}
测试:
public void myselfListenerTest(){
AbstractApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
animal a=(animal) context.getBean("myselfListener");
System.out.println(a.getSleepsString());
}