3

I found a strange thing while learning Spring tech.

I inject a java.lang.String type bean into a bean property which type is java.io.File, but the program still runs normally.

I want to know

  1. What happened internally?
  2. Is it a valid usage or a trick?

Here is the spring configuration file 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>

Here is my test classes.

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());
    }
}
1
  • I tested your code and it works. Thanks. Commented Apr 4, 2017 at 17:16

1 Answer 1

1

It is done by the PropertyEditors in your case the FileEditor

Check the documentation here for more details: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

Sign up to request clarification or add additional context in comments.

1 Comment

Will this work with AnnotationConfigApplicationContext? Look at my code in my question here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.