为什么原型范围中的自动装配变量仅在第一个实例中起作用

时间:2015-01-01 01:10:03

标签: spring spring-mvc dependency-injection scope resttemplate

我正在尝试自动安装RestTemplate,我正在使用why can I autowire or inject pojo but I can't autowire or inject RestTemplate中的建议。不幸的是,我遇到了第二次实例化的问题。变量restTemplate只能运行一次。之后,它为空。我想我可能在dispatcher-servletweb.xml配置中犯了一些错误。

我知道范围原型每次调用时都会创建一个新实例,但我不希望自动连线RestTemplate在第二个实例中为空。所有其他自动变量变量在每次调用时都能完美运行 我看到了一些类似的线程,所有这些线程最终得到了一些与创建范围代理相关的解决方案。我改为@Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)但我得到错误“只能在引用原型bean定义时为getBean方法指定参数”。老实说,我无法想象这是我的情况的正确方向,因为我只有restTemplate和context.getBean的第二个问题。

//the process starts here

    ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
                   display = context.getBean(Lo_DisplayHandler.class, request, response);

                         display.lastPage();

DisplayHandler

@Component
@Scope("prototype")
public class Lo_DisplayHandler extends Lo_Handler {
 //this constructor runs twice when the application start
       public Lo_DisplayHandler() {
              super();
       }

每次从上下文获取bean时都会运行此构造函数(context.getBean(Lo_DisplayHandler.class,request,response))。第一次创建Lo_DisplayHandler时,会填充restTemplate,但是从第二次开始,restTemplate为null

public Lo_DisplayHandler(HttpServletRequest request,HttpServletResponse response) {
    super();
    //get DB2 connection and set some data in session
}


@Autowired
private RestTemplate restTemplate;
 //restTemplate will exist only in the first time
LogDisplay _l = restTemplate.postForObject(RestProperties.getUrl() + RestProperties.getFirstpage(),_mas60010, LogDisplay.class);

MVC-调度-servlet.xml中

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans    
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">

           <context:annotation-config />
           <mvc:annotation-driven />
           <context:component-scan base-package="com.myCompany.mhe.common.controller, com.myCompany.mhe.log.handler, com.myCompany.mhe.utilities, com.myCompany.mhe.log.domain, com.myCompany.mhe.log.storedprocedure" />
           <context:property-placeholder location="classpath:restServices.properties"/>
           <mvc:resources mapping="/**" location="/" />

           <!—-
    If take the next three beans definition from here to applicationContext.xml and change contextConfigLocation to point to applicationContext.xml instead of mvc-dispatcher-servlet.xml my controller stops to work
    -->

           <bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
           <bean
               class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
               <property name="targetObject" ref="jacksonObjectMapper" />
               <property name="targetMethod" value="configure" />
               <property name="arguments">
                   <list>
                       <value type="com.fasterxml.jackson.databind.DeserializationFeature">READ_DATE_TIMESTAMPS_AS_NANOSECONDS</value>
                       <value>true</value>
                   </list>
               </property>
           </bean>

           <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
               <property name="messageConverters">
                   <list>
                       <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                           <property name="objectMapper" ref="jacksonObjectMapper" />
                       </bean>
                   </list>
               </property>
           </bean>


    </beans>

的web.xml

  <servlet>
          <servlet-name>mvc-dispatcher</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
          <servlet-name>mvc-dispatcher</servlet-name>
          <url-pattern>/</url-pattern>
   </servlet-mapping>

   <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
   </context-param>

   <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

//删除默认构造函数后的异常

[WARNING ] Exception encountered during context initialization - cancelling refresh attempt
Error creating bean with name 'lo_Controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.mhe.Mhe_Handler com.mycompany.mhe.common.controller.Lo_Controller.mhe_Handler; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lo_DisplayHandler' defined in file [C:\STS\wsRestTemplate\MHE_original\WebContent\WEB-INF\classes\com\mycompany\mhe\log\handler\Lo_DisplayHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mycompany.mhe.log.handler.Lo_DisplayHandler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mycompany.mhe.log.handler.Lo_DisplayHandler.<init>()
[ERROR   ] Context initialization failed
Error creating bean with name 'lo_Controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.mhe.Mhe_Handler com.mycompany.mhe.common.controller.Lo_Controller.mhe_Handler; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lo_DisplayHandler' defined in file [C:\STS\wsRestTemplate\MHE_original\WebContent\WEB-INF\classes\com\mycompany\mhe\log\handler\Lo_DisplayHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mycompany.mhe.log.handler.Lo_DisplayHandler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mycompany.mhe.log.handler.Lo_DisplayHandler.<init>()

0 个答案:

没有答案