一什么是Spring?
Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架
二如何在程序中获取Spring配置的bean呢?
方法一在初始化时保存ApplicationContext对象
代码
ApplicationContext ac =
new
FileSystemXmlApplicationContex(
applicationContextxml
);
acgetBean(
beanId
);
ApplicationContext ac = new FileSystemXmlApplicationContex(applicationContextxml);
acgetBean(beanId);说明这种方式适用于采用Spring框架的独立应用程序需要程序通过配置文件手工初始化Spring的情况
方法二通过Spring提供的工具类获取ApplicationContext对象
代码
import
orgsprntextsupportWebApplicationContextUtils;
ApplicationContext ac = WebApplicationContextUtils
getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac = WebApplicationContextUtils
getWebApplicationContext(ServletContext sc)
acgetBean(
beanId
);
acgetBean(
beanId
);
import
orgsprntextsupportWebApplicationContextUtils;
ApplicationContext ac = WebApplicationContextUtils
getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac = WebApplicationContextUtils
getWebApplicationContext(ServletContext sc)
acgetBean(
beanId
);
acgetBean(
beanId
);
方法三继承自抽象类ApplicationObjectSupport
说明抽象类ApplicationObjectSupport提供getApplicationContext()方法可以方便的获取到ApplicationContextSpring初始化时会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入
方法四继承自抽象类WebApplicationObjectSupport
说明类似方法三调用getWebApplicationContext()获取WebApplicationContext
方法五实现接口ApplicationContextAware
说明实现该接口的setApplicationContext(ApplicationContext context)方法并保存ApplicationContext 对象Spring初始化时会通过该方法将ApplicationContext 对象注入