1. 通常我们在java类中,如果想要获取applicationContext.xml中配置的bean,会采用下面方式:
importjavax.sql.DataSource;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.FileSystemXmlApplicationContext;public classSpringConfigTest
{public static void main(String[] args) throwsException
{
ApplicationContext ac= new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
DataSource datasource= (DataSource) ac.getBean("dataSource");
}
}
这种方式确实可以从applicationContext.xml中获取到指定id的Bean,但是效率很低,每次去getBean时都重新加载了applicationContext.xml文件,在web开发中是不建议直接这样用的,可以采用下面的方法
2. Spring中提供了获取ApplicationContext对象的接口,在 org.springframework.context.ApplicationContextAware中我们只需实现 ApplicationContextAware接口的setApplicationContext方法,然后在Spring的配置文件 applicationContext.xml中 注册实现ApplicationContextAware接口的类的类,并用静态的 ApplicationContext变量把ApplicationContext保存下来,就可以了(并在web.xml中配置只要配置了spring监听器,那么在服务启动时读取配置文件并为applicationContext赋值,然后就可以随心所欲的使用静态的ApplicationContext了
步骤1:写一个类实现ApplicationContextAware,并实现setApplicationContext()方法.
importorg.springframework.beans.BeansException;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ApplicationContextAware;public class SpringFactory implementsApplicationContextAware
{private staticApplicationContext context;/*** 实现setApplicationContext()*/
public voidsetApplicationContext(ApplicationContext context)throwsBeansException
{this.context =context;
}/*** 从applicationContext中获取指定id的bean
*@paramid要获取的springBean的id
*@return
*/
public staticObject getObject(String id) {
Object object= null;
object=context.getBean(id);returnobject;
}
}
步骤2:在spring的applicationContext.xml中配置该bean
步骤3:web.xml中要配置spring监听器(目的容器启动时就加载applicationContext.xml)
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
步骤 4. 现在开始就可以在项目中j使用SpringFactory类获取指定id的Bean了(必须服务器启动下,去测试,否则肯定是空指针异常)
public classDBUtil
{private staticDataSource dataSource;static{
dataSource= (DataSource) SpringFactory.getObject("dataSource");
}//获得连接
public static Connection getConnection() throwsSQLException
{returndataSource.getConnection();
}