现在applicationContext.xml定义bean,接下来
//初始化容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象
ScrenDriver screnDriver = context.getBean("screnDriver", ScrenDriver.class);
//使用对象
screnDriver.user();
Bean有效范围
- singleton (单例(只有一个实例))
<bean id="screnDriver" class="cn.test.controller.ScrenDriver" scope="singleton"></bean>
-prototype (每次引用都创建一个新的实例)
<bean id="screnDriver" class="cn.test.controller.ScrenDriver" scope="prototype"></bean>
Bean生命周期回调
-创建
public interface InitializingBean{
void afterPropertiesSet() throws Exception;
}
<bean id="screnDriver" class="cn.test.controller.ScrenDriver" init-method="init">
public class init {
public void init() {
System.out.println("init");
}
}
-销毁
public interface DisposableBean{
void destroy() throws Exception;
}
<bean id="screnDriver" class="cn.test.controller.ScrenDriver" destroy-method="cleanup">
public class cleanup {
public void cleanup() {
System.out.println("clean");
}
}
容器关闭
((ConfiggurableApplicationContext)context).close()