1.今天想使用ApplicationContextAware接口方式去获取上下文环境,从而去获取bean,自己照着例子去写了一遍,但是最后还是报错,找不到这个bean,貌似实现了ApplicationContextAware的这个类根本就没有被Spring初始化的时候初始化执行setApplicationContext()方法(我已经在配置文件配置了这个bean),下面是我的代码:
2.工程代码
(1)web.xml
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> spring-test contextConfigLocation classpath*:config/spring/local/appcontext-*.xml org.springframework.web.context.ContextLoaderListener index.jsp
(2).spring配置文件,我用的是idea,配置文件在config/spring/local下,Resource下面
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd ">
(3).SpringTest.java
package com.fcc.spring.test; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.annotation.Resource; public class SpringTest implements ApplicationContextAware{ private static ApplicationContext applicationContext; public static void main(String[] args){ HelloWorld obj = (HelloWorld)SpringTest.getBean("helloWorld"); System.out.println("obj = " + obj); System.out.println("The message value is " + obj.getMessage()); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("applicationContext before : " + applicationContext); SpringTest.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext(){ return applicationContext; } public static Object getBean(String name) throws BeansException{ System.out.println("applicationContext = " + applicationContext); return applicationContext.getBean(name); } }
HelloWorld的代码我就不贴了,就是一个简单的JavaBean,有个message:String属性
我理解的初始化顺序是这样的:
启动tomcat容器,加载web.xml,建立整个容器(Servlet容器,这里是tomcat吧)的上下文,ServletContext,这时web.xml有个监听器,就是ContextLoaderListener,监听到这个事件,就会去扫描spring配置文件,默认是applicationContext.xml文件(classpath,idea是Resource下),如果自定义,就应该如web.xml中的
我前几天也遇到同样的问题,我的情况是在一个通过反射实例化的类里,用spring管理的实例,我也写了一个这样的类来获取spring实例,开始怎么都无法注入,后来我加了lazy-init="false"就可以了,我原来用spring3的时候都不用加,这次用的spring4,希望对你有帮助
SpringTest(实现ApplicationContextAware的类)
必须要加入spring bean
去管理,可以用Compnent
注解或在xml
文件去配。
不然spring
不会处理这个,这也是applicationContext
为null
的原因。
@青楼有罪 ApplicationContextAware这个中有getBean()方法,你为什么还要实现它,写自己的getBean()方法,直接用它的方法不行么?不理解。这么多代码,不就是说明了spring通过application context来获取java bean的么?
ioc容器未初始化,先实例化一个ApplicationContext
和web容器有什么关系,加载spring容器方法不只有一种。
貌似我找到问题所在了,我真是蠢,真的蠢。。。
都说了tomcat容器启动才会去启动web.xml文件,但是我写的是控制器程序,根本就没有tomcat。。。