用于Tomcat服务器中WAR导出的Spring文件I / O.

时间:2014-02-13 06:35:45

标签: java spring file-io tomcat7

我想在Spring应用程序中执行文件I / O.

我进入了XML路径,但一旦运行,我得到的只是BeanCreationException错误。


  1. 我在file-locations.properties中创建了my_spring_app/src/main/resources,其内容如下:

    # location of desired files
    
    dir.server=/home/user/webapps/my_spring_app/WEB-INF/classes/
    dir.local=D:/resources
    
  2. 他们说要修改application-context.xml文件将被声明的.properties,以便Spring可以识别它(???)。

    <context:property-placeholder location="classpath*:file-locations.properties" properties-ref="filePathProps" />
    
  3. 调用.properties图层中的Service文件进行文件I / O.

    @Value("#{filePathProps.dir.local}")
    private String PATH_FILES;
    
    System.out.println(PATH_FILES); // so far null
    

    我尝试了多种组合:@Value("#{filePathProps.dir.local}")@Value("${filePathProps.dir.local}")@Value("#{dir.local}")@Value("${dir.local}"),所有这些组合都返回了错误。

  4. 我会将BufferedReaderBufferedWriter用于这些文件。


  5. 完整的`application-context。

    <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"
      xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
      xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.2.5xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.5.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.5.xsd
        http://www.springframework.org/schema/util   
        http://www.springframework.org/schema/util/spring-util.xsd">
    
      <!-- Auto-detect components -->
    
      <context:component-scan base-package="my.spring.app" />
    
      <bean id="MyService1"
        class="my.spring.app.service.impl.MyService1Impl" />
      <bean id="MyService2Service"
        class="my.spring.app.service.impl.MyService2ServiceImpl" />
      <bean id="MyService3Service"
        class="my.spring.app.service.impl.MyService3ServiceImpl" />
    
      <mvc:annotation-driven />
    
      <!-- Application Message Bundle -->
      <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
        <property name="cacheSeconds" value="3000" />
      </bean>
    
      <!-- files??? -->
      <context:property-placeholder location="classpath*:file-locations.properties"
        properties-ref="filePathProps" />
    
    </beans>
    

    以下是web.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
      id="WebApp_ID" version="3.0">
    
      <display-name>my_spring_app</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
    
      <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
      <!-- Error pages -->
      <location>/WEB-INF/jsp/error/400.jsp</location>
      <error-page>
        <error-code>400</error-code>
      </error-page>
    
      <error-page>
        <error-code>403</error-code>
        <location>/WEB-INF/jsp/error/403.jsp</location>
      </error-page>
    
      <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/jsp/error/404.jsp</location>
      </error-page>
    
      <error-page>
        <error-code>405</error-code>
        <location>/WEB-INF/jsp/error/405.jsp</location>
      </error-page>
    
      <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/jsp/error/500.jsp</location>
      </error-page>
    
      <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/jsp/error/exception.jsp</location>
      </error-page>
    
    </web-app>
    

    以下是spring-servlet.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:p="http://www.springframework.org/schema/p"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
      <context:component-scan base-package="my.package.controller" />
      <context:component-scan base-package="my.package.service" />
    
      <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
          value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
      </bean>
    
      <!--This tag allows for mapping the DispatcherServlet to "/" (all extensions 
        etc) -->
      <mvc:default-servlet-handler />
    
      <mvc:annotation-driven />
      <mvc:resources location="/resources/**, classpath:resources"
        mapping="/resources/**" />
      <mvc:resources mapping="/css/**" location="/resources/css/*" />
      <mvc:resources mapping="/js/**" location="/resources/js/*" />
      <mvc:resources mapping="/images/**" location="/resources/images/*" />
      <mvc:resources mapping="/weka/**" location="/resources/weka/*" />
    
    </beans>
    

    部分堆栈跟踪(full here):

    org.springframework.web.servlet.DispatcherServlet initServletBean
    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private my.package.service.CalcService my.package.controller.CalcController.calcService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'calcService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void my.package.service.impl.MyServiceImpl.setMyService2(my.package.service.MyService2); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'calcArffService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String my.package.service.impl.MyService2Impl.PATH_FILES; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'filePath' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
        at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
        at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
        at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
        at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
        at javax.servlet.GenericServlet.init(GenericServlet.java:160)
        at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
        at java.util.concurrent.FutureTask.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
    

    我做了一个名为FilePath的POJO:

    public class FilePath {
    
      private String filePath;
    
      public String getFilePath() {
        return filePath;
      }
    
      public void setFilePath(String filePath) {
        this.filePath = filePath;
      }
    
      @Override
      public String toString() {
        return "FilePath [filePath=" + filePath + "]";
      }
    
    }
    

    我将以下内容添加到spring-servlet.xmlapplication-context.xml

    <context:component-scan base-package="src/main/resources" />
    <context:property-placeholder location="classpath*:file-locations.properties" />
    <bean id="filePaths"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location" value="classpath:file-locations.properties" />
    </bean>
    <bean class="ph.edu.upm.agila.gtmeren.bosom.domain.FilePath">
      <property name="filePath" value="${filePath}" />
    </bean>
    

    但即使我把这些新代码放在application-context.xml

    <context:property-placeholder location="classpath:file-locations.properties" />
    <bean class="my.package.FilePath">
        <property name="filePath" value="file-location.properties" />
    </bean>
    

    System.out.println(PATH_FILES);的输出为${dir.local}

3 个答案:

答案 0 :(得分:0)

放手一步。

  1. 定义属性占位符

    <context:property-placeholder location="classpath*:file-locations.properties"/>

  2. 使用dir.server

  3. 访问该媒体资源
  4. 使用$

  5. 注入值
  6. 因此你的bean看起来像是

    @Value(“$ {dir.local}”)
    private String PATH_FILES;

  7. 现在真正的问题是财产是否会被加载。

    1. 如果您在部署到服务器后进行测试,请确保该文件位于/WEB-INF/classes/file-locations.properties

    2. 如果你正在做一个junit sing eclipse,请确保在project-properties-&gt;中的文件。 java构建路径 - &gt;来源标签。 src/main/resources包含在选项中,包括所有

    3. <强> EDITED

      在web.xml中添加缺少web.xml中的配置,如果application-context.xml在classpath内的spring目录中,则需要在web.xml中添加context参数,如下所示

       <context-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>classpath:spring/application-config.xml</param-value>
          </context-param>
      
      <listener>
              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          </listener>
      

答案 1 :(得分:0)

在继续之前,您需要先查看Spring MVC documentation。如果不是全部,您至少应该阅读上下文层次结构以及哪个ApplicationContext由哪个Web应用程序组件加载。

目前,您的application-context.xml绝对没有用处。正如您所示,您的应用程序中没有任何内容正在使用它。您的DispatcherServlet正在从spring-servlet.xml加载其配置。您需要在那里声明property-placeholder

字段本身应该是

@Value("${dir.local}")
private String PATH_FILES;

Spring文档也详细解释了SpEL expressions

答案 2 :(得分:0)

以下是我没有任何错误的方法:

  1. 我在src/resources
  2. 中放置了I / O所需的文件
  3. 运行Tomcat后,我会搜索这些文件所在的位置,并且它们位于C:/tomcat/webapp/my_app/WEB-INF/classes/resources
  4. 我创建了一个将C:/tomcat/webapp/my_app/WEB-INF/classes/resources连接到我的文件的函数。
  5. 例如,我想写一个文件,我只是这样做:

    String filePath = myService.getAbsolutePath() + "file.dat";
    BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
    

    其中.getAbsolutePath()实现只返回MyService类中的文件路径!

  6. 注意:一旦上传到服务器,只需重复第二个 - 在放置文件的服务器中进行搜索,并将其替换为.getAbsolutePath()的内容!

    你去吧!