java - Spring 设置 java.io.File 属性使用 java.lang.String bean

标签 java spring

在学习Spring技术的过程中,我发现了一件奇怪的事情。

我在类型为java.io.File的bean属性中注入(inject)了一个java.lang.String类型的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());
    }
}

最佳答案

这是由 PropertyEditors 在您的案例中完成的 FileEditor

查看此处的文档以获取更多详细信息:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

关于java - Spring 设置 java.io.File 属性使用 java.lang.String bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759531/

相关文章:

java - @ControllerAdvice 不返回 json 响应

spring - 用于 HikariCP + Spring + MS SQL Server 的 JTDS 配置

java - 从内存而不是磁盘读取文件

java - 如何跟踪可能重叠的应用程序不同组件的不同性能改进?

java - 异步 Java ReSTLet Web 服务的示例?

java - 持久化JPA后获取UniqueID

java - 在 MySQL 中插入多行

java - 在 xws-security for Spring-WS 中支持 X509PKIPathv1

mysql - Hibernate QuerySyntaxException,表未映射

java - 转换 Hibernate 列表而不初始化它