java类中从spring的ApplicationContext.xml中获取bean
1. 通常我们在java类中,如果想要获取applicationContext.xml中配置的bean,会采用下面方式:
import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class SpringConfigTest { public static void main(String[] args) throws Exception { 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()方法.
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringFactory implements ApplicationContextAware { private static ApplicationContext context; /** * 实现setApplicationContext() */ public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } /** * 从applicationContext中获取指定id的bean * @param id要获取的springBean的id * @return */ public static Object getObject(String id) { Object object = null; object = context.getBean(id); return object; } }
步骤2:在spring的applicationContext.xml中配置该bean
<!-- 注入SpringFactory类 --> <bean id="springfactory" class="com.espeed.util.SpringFactory"> </bean>
步骤3:web.xml中要配置spring监听器(目的容器启动时就加载applicationContext.xml)
<!-- 配置spring监听器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
步骤 4. 现在开始就可以在项目中j使用SpringFactory类获取指定id的Bean了(必须服务器启动下,去测试,否则肯定是空指针异常)
public class DBUtil { private static DataSource dataSource; static { dataSource = (DataSource) SpringFactory.getObject("dataSource"); } //获得连接 public static Connection getConnection() throws SQLException { return dataSource.getConnection(); }