Spring集合java.io.File属性使用java.lang.String bean

Spring集合java.io.File属性使用java.lang.String bean,java,spring,Java,Spring,我在学习Spring技术时发现了一件奇怪的事情 我将java.lang.String类型bean注入类型为java.io.File的bean属性,但程序仍然正常运行 我想知道 内部发生了什么 这是一个有效的用法还是一个诡计 这是spring配置文件stringtofile.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"

我在学习Spring技术时发现了一件奇怪的事情

我将
java.lang.String
类型bean注入类型为
java.io.File
的bean属性,但程序仍然正常运行

我想知道

  • 内部发生了什么
  • 这是一个有效的用法还是一个诡计
  • 这是spring配置文件
    stringtofile.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:c="http://www.springframework.org/schema/c"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
           default-lazy-init="true">
    
        <bean id="file_str"
              class="java.lang.String"
              c:_="C:\tmp\test.hi"/>
    
        <bean id="file"
              class="stringtofile.FileWrapper"
              p:file-ref="file_str"/>
    </beans>
    

    在您的案例中,它是由PropertyEditor完成的


    查看此处的文档以了解更多详细信息:

    我测试了您的代码,它可以正常工作。谢谢。这是否适用于AnnotationConfigApplicationContext?请查看我的
    package stringtofile;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import java.io.File;
    
    public class FileWrapper {
        File file;
    
        public File getFile() {
            return file;
        }
    
        public FileWrapper setFile(File file) {
            this.file = file;
            return this;
        }
    
        public static void main(String[] args) {
            ApplicationContext ctx =
                    new ClassPathXmlApplicationContext("stringtofile.xml");
            FileWrapper fileWrapper =
                    (FileWrapper) ctx.getBean("file");
            System.out.println(fileWrapper.getFile());
        }
    }