相比前两大框架,spring的使用就简单的多,导入spring相关依赖包后,在javase中可以通过以下代码获得
-
ApplicationContext appl = new ClassPathXmlApplicationContext("bean.xml");
-
System.out.printf(appl+"\n");
-
News new2=(News) appl.getBean("news");//通过使用getBean获取代理对象的代理类
-
-
//spring根据配置文件信息,负责创建News类,并且为News的相关属性赋值-这种由spring为对象赋值的叫做
-
-
//控制反转即(Inversion of control ioc)
-
-
System.out.printf(new2.getContent()+"\n");
对应的bean配置文件如下
-
<?xml version="1.0" encoding="UTF-8"?>
-
<beans xmlns=""
-
xmlns:xsi=""
-
xmlns:aop=""
-
xmlns:tx=""
-
xmlns:context=""
-
xsi:schemaLocation="
-
/spring-beans-2.5.xsd
-
-
/spring-aop-2.5.xsd
-
-
/spring-context-2.5.xsd
-
-
/spring-tx-2.5.xsd">
-
<bean id="news" class="model.News">
-
<property name="content" value="12312"></property>
-
</bean>
-
<bean id="emailListener" class="model.EmailListener">
-
-
</bean>
-
<!-- <import resource="applicationContext-db.xml"/>
-
<import resource="applicationContext-person.xml"/> -->
-
</beans>
spring对外提供了很多接口,并且以观察者的模式进行监听。首先时间发生源要继承ApplicationEvent对象,然后事件监听器要实现ApplicationListener,在应用的时候只要调用ApplicationContext.pushEvent();就可以触发事件的相应。以下是源代码
-
package model;
-
-
import org.springframework.context.ApplicationEvent;
-
import org.springframework.context.ApplicationListener;
-
-
public class EmailListener implements ApplicationListener {
-
-
@Override
-
public void onApplicationEvent(ApplicationEvent applicationevent) {
-
// TODO Auto-generated method stub
-
-
if(applicationevent instanceof EmailEvent){
-
EmailEvent evt =(EmailEvent)applicationevent;
-
System.out.printf("需要发邮件的接收地址:"+evt.getName());
-
-
}else{
-
-
System.out.printf("容器内部的事件");
-
}
-
-
}
-
-
}
-
package model;
-
-
import org.springframework.context.ApplicationEvent;
-
-
public class EmailEvent extends ApplicationEvent {
-
private String name;
-
private String address;
-
/**
-
* application 中的事件机制是以观察者模式运行的,首先实现
-
*继承ApplicationEvent中
-
* @param source
-
*/
-
public EmailEvent(Object source) {
-
super(source);
-
// TODO Auto-generated constructor stub
-
-
}
-
public EmailEvent(Object source,String name,String address){
-
super(source);
-
this.name=name;
-
this.address=address;
-
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
public String getAddress() {
-
return address;
-
}
-
public void setAddress(String address) {
-
this.address = address;
-
}
-
-
}
触发代码
-
EmailEvent evet = new EmailEvent("123","12313","123123");
-
appl.publishEvent(evet);
阅读(187) | 评论(0) | 转发(0) |