Spring中ApplicationContext的机制
2016/6/3 17:01:53 seventeenWen
ApplictionContext的实现机制,在Spring框架中有ApplicationEvent抽象类和ApplicationLostenner接口
ApplicationEvent源码:
public abstract class ApplicationEvent extends EventObject {
private static final long serialVersionUID = 7099057708183571937L;
private final long timestamp;
public ApplicationEvent(Object source) {
super(source);
this.timestamp = System.currentTimeMillis();
}
public final long getTimestamp() {
return this.timestamp;
}
}
ApplicationListener接口源码:
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E event);
}
我们要实现自己的Application事件机制,首先定义一个类继承自ApplicationEvent
,这样我们就可以通过Spring来进行管理。
public class MyEvent extends ApplicationEvent {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MyEvent(Object source) {
super(source);
}
// --------构造注入-----------
public MyEvent(Object source, String name) {
super(source);
this.name = name;
}
private static final long serialVersionUID = 1L;
}
我们有了Event之后还需要一个Listener来监听Event中发生的事件,实现ApplicationListener接口,并且实现它的一个方法:
onApplicationEvent(ApplicationEven event):每当Event中发生事件时,此方法都会触发。
public class MyListener implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent event) {
//判断一下是不是我们自己定义的MyEvent的对象
if(event instanceof MyEvent){
MyEvent eve = (MyEvent) event;
System.out.println("我的名字:"+eve.getName());
}else{
System.out.println("不是我们自己的Event");
}
}
}
接下来我们在xml配置文件中将Listener配置进去,测试类TestSpring
public class TestSpring {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
MyEvent event =new MyEvent("test","----SeventeenWen----");
//publish用来主动触发Event
ctx.publishEvent(event);
}
}
在consol上我们就能看到结果了
不是我们自己的Event
我的名字:----SeventeenWen----
总结
让我们再来总结一下,ApplicationContext机制流程,首先是加载配置文件Resource,
继承ApplicationContextEvent抽象类,实现ApplicationListener接口,配置配置文件。
程序发布Event事件,激活监听事件。
Spring中的Bean
Bean包含的属性
配置文件中的Bean通常会有两个属性
<bean id="" class=""></bean>
**id:**Bean在Spring中的唯一标识。
class: 指定Bean的具体实现类,因为Spring底层是用反射创建的,所以不能是抽象类。
Bean的作用域
- **singleton:**Spring默认作用域,单例模式,在singleton作用域中的Bean只有生成一个对象
- prototype:每次通过getBean获取对象时都会产生一个新的对象。
- request:对于一次HTTP请求,request域中的Bean只会生成一个对象,
- session:对于一次HTTP会话,session域中只生成一个对象,
- global session:每个全局session都会生成一个对象。只在使用portletcontext有效。