【问题标题】:The value to the property that is set in the spring bean is getting null when using使用时,在 spring bean 中设置的属性的值变为 null
【发布时间】:2018-02-02 16:54:55
【问题描述】:

这是我的 beans.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:context="http://www.springframework.org/schema/context"
    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">

<context:property-placeholder location="file:/C:/local/fts.properties" />

    <bean id="shredFilesUnderTimePeriod" class="com.qvc.supplychain.app.delete.ShredFilesUnderTimePeriod">
        <property name="fileLocation" value="${LOCAL_FILE_DIR}/FileTransferIntegrationServices/ftpArchive"/>
    </bean>

</beans>

这是我的应用程序类:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class ShredFilesUnderTimePeriod {

    public Logger logger = Logger.getLogger(this.getClass());

    private final static int DAYS_LIMIT = 2;

    private String fileLocation;

    private static long currentTimeInMillis;

    public ShredFilesUnderTimePeriod() {
        shredFilesFromDirectory();
    }

    private void shredFilesFromDirectory() {
        logger.info("Deleting the obsolete files");
        currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
        Date currentDate = new Date(currentTimeInMillis);
        logger.info("Today's date: " + "" + currentDate + "\n");
        try {
            File loadFilesFromTheDirectory = new File(fileLocation);
            if (!loadFilesFromTheDirectory.isDirectory()) {
                throw new FileNotFoundException("Is not a directory");
            } else {
                for (File file : loadFilesFromTheDirectory.listFiles()) {
                    if (file.isDirectory()) {
                        for (File subDirectoryFile : file.listFiles()) {
                            deleteFile(subDirectoryFile);
                        }
                    } else {
                        deleteFile(file);
                    }
                }
                logger.info("Obsolete files deletion got completed");
            }

        } catch (FileNotFoundException eMsg) {
            eMsg.printStackTrace();
        } catch (Exception eMsg) {
            logger.error("Error while shredding obsolete files. Cause: " + eMsg.getStackTrace());
            System.out.println("Error while shredding obsolete files. Cause: " + eMsg.getStackTrace());
        } finally {
            //System.exit(0);
        }
    }

    private void deleteFile(File file) {
        long totalNumberOfDays = 0L;
        Date fileCreatedDate = null;
        try {
            if (file.isDirectory()) {
                throw new FileNotFoundException("Is not a directory");
            }
            fileCreatedDate = new Date(file.lastModified());
            logger.info(file.getName() + " file is created or last modified on: " + fileCreatedDate
                    + ", total number of days present: " + totalNumberOfDays);
            totalNumberOfDays = TimeUnit.DAYS.convert(currentTimeInMillis - fileCreatedDate.getTime(),
                    TimeUnit.MILLISECONDS);
            if (totalNumberOfDays > DAYS_LIMIT) {
                file.delete();
            }
        } catch (FileNotFoundException eMsg) {
            eMsg.printStackTrace();
        } catch (Exception eMsg) {
            logger.error("Error while shredding obsolete files. Cause: " + eMsg.getStackTrace());
        }
    }

    public String getFileLocation() {
        return fileLocation;
    }

    public void setFileLocation(String fileLocation) {
        this.fileLocation = fileLocation;
    }

}

现在的问题是 fts.properties 文件正在加载,但属性的值:“fileLocation”未设置。我很困惑,即使在我尝试给出直接值之后,它在调试时仍然显示为空。我想知道哪里出了问题。我希望动态设置此字段/属性的值。任何帮助表示赞赏。

【问题讨论】:

  • 属性在构造函数调用之后设置。因此,您不能在构造函数中调用该方法并认为填充了 fileLocation。您应该在属性集之后创建一个初始化方法
  • 非常感谢您。它正在工作!
  • 尝试在设置器文件位置上使用 Autowired 注释。并使用 Value annotation 传递文件路径。 应该在配置文件中使用。

标签: xml spring properties javabeans


【解决方案1】:

正如 Angelo Immediata 在评论中提到的,我尝试使用 init-method 属性,现在可以看到代码正常工作。我所做的更改:

<?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:context="http://www.springframework.org/schema/context"
    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">

<context:property-placeholder location="file:/C:/MY_QVC/fts.properties" />

    <bean id="shredFilesUnderTimePeriod" class="com.qvc.supplychain.app.delete.ShredFilesUnderTimePeriod" init-method="shredFilesFromDirectory">
        <property name="fileLocation" value="${LOCAL_FILE_DIR}/FileTransferIntegrationServices/ftpArchive"/>
    </bean>

</beans>

并且我已经删除了默认构造函数。

【讨论】:

    【解决方案2】:

    事实上,在您的情况下,这个 Filelocation 将始终为空,原因很简单,就是他们在 spring 文档中提到的内容

    Spring 容器在创建容器时验证每个 bean 的配置。但是,在实际创建 bean 之前,不会设置 bean 属性本身。

    查看 this section

    在您的 java 代码中,您在容器设置之前在构造函数中使用此属性

    你可以通过多种方式解决这个问题,其中一种是创建一个带有String参数的构造函数并将xml中的属性更改为construct-arg

     <constructor-arg name="fileLocation" value="${LOCAL_FILE_DIR}/FileTransferIntegrationServices/ftpArchive"></constructor-arg>
    

    在构造函数中设置你的属性并使用它——你让它像任何其他依赖项一样需要

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多