簡體   English   中英

Spring設置java.io.File屬性使用java.lang.String bean

[英]Spring set java.io.File property use java.lang.String bean

在學習Spring技術時我發現了一件奇怪的事情。

我將一個java.lang.String類型的bean注入一個類型為java.io.File的bean屬性,但該程序仍然正常運行。

我想知道

  1. 內部發生了什么?
  2. 它是有效的用法還是技巧?

這是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>

這是我的測試課程。

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());
    }
}

它由PropertyEditor完成,例如FileEditor

有關詳細信息,請查看此處的文檔: http//docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM