如何创建Path bean

Rae*_*ald 10 java spring factory

我需要我的Spring应用程序上下文包含一个bean(Java 7)Path对象,它具有固定的(已知的)路径名.我应该使用什么XML bean定义?

这种豆有一些复杂性:

由于对象是-A Path,将class豆的应该是Path:

 <bean name="myPath" class="java.nio.file.Path"/>
Run Code Online (Sandbox Code Playgroud)

我需要指出要使用的静态工厂方法,这似乎需要一个factory-method属性.但是工厂方法属于java.nio.file.Paths类而不是java.nio.file.Path类,所以我假设以下方法不起作用:

 <bean name="myPath" class="java.nio.file.Path"
    factory-method="java.nio.file.Paths.get"/>
Run Code Online (Sandbox Code Playgroud)

最后,我需要给出工厂方法的参数.我怎么做?使用嵌套constructor-arg(sic)元素?那么,这样的事情呢?

 <bean name="myPath" class="java.nio.file.Path"
    factory-method="java.nio.file.Paths.get">
    <constructor-arg value="/my/path/name"/>
 </bean>
Run Code Online (Sandbox Code Playgroud)

但这不起作用:Springs抛出一个BeanCreationException,抱怨"找不到匹配的工厂方法:工厂方法'java.nio.file.Paths.get()'."

Rae*_*ald 9

经过一些试验pingw33n的答案,我发现这有效:

 <bean id="myPath" class="java.nio.file.Paths" factory-method="get">
    <constructor-arg value="/my/path" />
    <constructor-arg><array /></constructor-arg>
 </bean>
Run Code Online (Sandbox Code Playgroud)

注意:

  • 工厂类的名称(而不是对象类)作为class属性的值.
  • 给出一个额外的空array构造函数参数,强制选择工厂方法的正确重载.这避免了必须转向构建文件URI的循环路线.