【问题标题】:Autowire Application ContextAutowire 应用程序上下文
【发布时间】:2012-11-21 11:22:30
【问题描述】:

我正在尝试将 WebApplicationContext 自动装配到我在 Spring MVC 项目中创建的类 ImageCreatorUtil 中。在使用应用程序上下文的类中执行方法时,我总是收到 NPE。请务必注意,此方法由另一个配置文件中定义的 ApplicationListener 调用。我不确定为什么自动装配不起作用。谁能给点建议?

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        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-3.1.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="org.springframework.data.web.PageableArgumentResolver" />
        </mvc:argument-resolvers>
    </mvc:annotation-driven>

    <!-- Intercept request to blog to add paging params -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/blog/**"/>
            <bean class="org.tothought.spring.interceptors.PageableRequestHandlerInterceptor" />
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="org.tothought.spring.interceptors.LookupHandlerInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <mvc:resources location="/resources/" mapping="/resources/**" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
    </bean>

    <context:component-scan base-package="org.tothought.spring.**" />

</beans>

ImageCreatorUtil.java

@Component
public class ImageCreatorUtil {

    static Logger logger = LoggerFactory.getLogger(ImageCreatorUtil.class);
    static final String IMAGE_PATH_FRAGMENT = "/resources/images/resume/skills/uploaded-icons/";

    @Autowired
    private WebApplicationContext context;

    /**
     * Creates the provided file in the resources directory for access by the
     * web application.
     * 
     * @param appContext
     * @param image
     */
    public void storeImage(Image image) {
        if (image != null) {
            String realPath = ((WebApplicationContext)context).getServletContext().getRealPath("/");
            File tmpFile = new File(realPath + IMAGE_PATH_FRAGMENT + image.getName());

            try {
                logger.info("Saving image to :" + tmpFile.getAbsolutePath());
                FileUtils.writeByteArrayToFile(tmpFile, image.getFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:property-placeholder location="classpath:META-INF/db/db.properties" />
    <context:annotation-config/>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/to_thought" />
        <property name="username" value="${db.user}" />
        <property name="password" value="${db.password}" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="toThought" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <jpa:repositories base-package="org.tothought.repositories"/>

    <!-- Application Listeners -->
    <bean id="lookupLoader" class="org.tothought.spring.listeners.LookupLoaderApplicationListener" /> 
    <bean id="imageLoader" class="org.tothought.spring.listeners.ImageLoaderApplicationListener" /> 
</beans>

控制台错误

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.NullPointerException
    at org.tothought.spring.utilities.ImageCreatorUtil.storeImage(ImageCreatorUtil.java:34)
    at org.tothought.spring.listeners.ImageLoaderApplicationListener.onApplicationEvent(ImageLoaderApplicationListener.java:29)
    at org.tothought.spring.listeners.ImageLoaderApplicationListener.onApplicationEvent(ImageLoaderApplicationListener.java:1)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:97)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:324)

【问题讨论】:

  • @Amber 谢谢,有什么建议吗?
  • 我已经为您发布了答案。它就像“自动装配”在 Spring 调用一个方法时起作用,而不是当你使用它的对象显式调用某个方法时(它当然是由你创建的,而不是 Spring 通过自动装配创建的)。
  • 我有些怀疑..您实际上是在自动装配哪一个。是 applicationcontext.xml 还是 spring.xml...对不起我是学习者
  • 我正在使用 Spring-MVC,它为调度程序 servlet 和根应用程序指定上下文。这就是为什么你会看到两个配置文件。
  • 我明白了..您正在自动装配 servlet-context.xml 并且 ImageUtilCreate 类是由您创建的(使用新的)..所以 spring 无法进行链式自动装配..

标签: java spring spring-mvc


【解决方案1】:

我已经尝试过您的代码。上下文的自动装配适用于任何控制器类中的上下文,但当我使用类的对象调用方法时它不起作用。因此,如果您执行以下操作:

你的控制者:

@Autowired
private ImageCreatorUtil icu;

public String controllerMethod(....) {
    icu.storeImage();
}

您的 application-context.xml :

<bean id="icu" class="****.controller.ImageCreatorUtil"/>

然后自动装配就可以正常工作了。我会尝试向您更新这种行为的原因。

【讨论】:

  • 我知道问题是什么,您的回答有助于解决问题。当您在ApplicationListener 中创建ImageCreatorUtil 的新实例时,它没有帮助。哇!我需要在ApplicationListener 中自动连接ImageCreatorUtil
  • 我找不到任何说明这一事实的文件,但原则似乎是,当对任何属性使用“自动装配”时,创建对象的责任并因此通过“自动装配”向该对象提供所有必需的资源在于与春天。但是当我们使用“new”关键字自己创建一个新对象时,Spring 容器无法控制对象的创建,因此“自动装配”属性为“null”。
  • 说得好,我有点错过了依赖注入这一点。感谢您的宝贵时间。
  • 请参考:stackoverflow.com/questions/10997092/… 它提供了答案。
猜你喜欢
  • 1970-01-01
  • 2015-08-31
  • 2016-05-20
  • 2012-07-19
  • 2019-08-13
  • 2014-06-24
  • 2011-10-31
  • 2011-07-26
  • 2012-02-24
相关资源
最近更新 更多