在学习Spring技术的过程中,我发现了一件奇怪的事情。
我在类型为java.io.File
的bean属性中注入(inject)了一个java.lang.String
类型的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>
这是我的测试类。
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/