本文转自Javaeye,文中内容不代表本站观点,仅提供参考。 前几天看到网友总结的自学经验,觉得说得很好,引文:光看别人骑自行车很容易,那么是不是看了几百遍别人怎么骑自行车你也就马上能骑着走了呢?不摔跤是不可能学会的。
还有就是要经常总结:刚才说到会摔跤,那么这时候就要总结遇到的问题,这样下次再遇到就不会再去回忆了.好记性不如烂笔头.注释,如果今天不写,那么以后只会越来越忙,以后再也没时间写注释了.Ifyoudoesn'thavetimetodoittoday,thenwhendoyouhavetimetodoittomorrow?
所以今天就写个Spring的消息和事件实例。
1、JavaBean:User.java
packagecn.xy.hw;
/***//**
*@authorhanwei
*
*/
publicclassUser...{
privateStringname;
privateintage;
publicintgetAge()...{
returnage;
}
publicvoidsetAge(intage)...{
this.age=age;
}
publicStringgetName()...{
returnname;
}
publicvoidsetName(Stringname)...{
this.name=name;
}
}
2、用于国际化的两个消息资源文件:xiyou_en_US.properties和xiyou_zh_CN.properties
userloginuser...{0}loginat...{1}
和
userlogin使用者...{0}于...{1}登入
自定义下雨的事件:RainEvent.java
packagecn.xy.hw;
importorg.springFramework.context.ApplicationEvent;
/***//**
*@authorhanwei
*
*/
publicclassRainEventextendsApplicationEvent...{
publicRainEvent(Objectarg0)...{
super(arg0);
System.out.println("乌云密布、闪电、打雷,紧接着,下起了瓢泼大雨。");
}
}
下雨事件监听器:RainListener.java
packagecn.xy.hw;
importorg.springframework.context.ApplicationEvent;
importorg.springframework.context.ApplicationListener;
/***//**
*@authorhanwei
*
*/
publicclassRainListenerimplementsApplicationListener...{
/**//*(non-Javadoc)
*@seeorg.springframework.context.ApplicationListener#onApplicationEvent(
org.springframework.context.ApplicationEvent)
*/
publicvoidonApplicationEvent(ApplicationEventarg0)...{
if(arg0instanceofRainEvent)...{
System.out.println("唐僧大喊:" arg0.getSource() "赶快收衣服喽!");
}
}
}
配置文件:applicationContext.XML
<!--sp-->xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<beanid="user"class="cn.xy.hw.User"abstract="false"
lazy-init="default"autowire="default"dependency-check="default">
<propertyname="name">
<value>hanweivalue>
property>
<propertyname="age">
<value>20value>
property>
bean>
<beanid="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
abstract="false"lazy-init="default"autowire="default"
dependency-check="default">
<propertyname="basename"value="xiyou">property>
bean>
<beanid="listener"class="cn.xy.hw.RainListener"abstract="false"