I need my Spring application context to include a bean that is a (Java 7) Path
object, with a fixed (known) path-name. What XML bean definition should I use?
This kind of bean has some complications:
Path
is an interface, and Path
objects should be created using the Paths.get(String...)
static factory method.Paths.get(URI)
.As the object is-a Path
, the class
of the bean should be Path
:
<bean name="myPath" class="java.nio.file.Path"/>
I need to indicate the static factory method to use, which would seem to require a factory-method
attribute. But the factory method belongs to the java.nio.file.Paths
class rather than the java.nio.file.Path
class, so I assume the following would not work:
<bean name="myPath" class="java.nio.file.Path"
factory-method="java.nio.file.Paths.get"/>
Lastly, I need to give the arguments for the factory method. How do I do that? Using nested constructor-arg
(sic) elements? So, something like this?
<bean name="myPath" class="java.nio.file.Path"
factory-method="java.nio.file.Paths.get">
<constructor-arg value="/my/path/name"/>
</bean>
But that does not work: Springs throws a BeanCreationException
, complaining of "No matching factory method found: factory method 'java.nio.file.Paths.get()'."
Different Methods to Create a Spring BeanCreating Bean Inside an XML Configuration File (beans. xml) Using @Component Annotation. Using @Bean Annotation.
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.
@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .
After some experimenting with pingw33n's answer, I found this worked:
<bean id="myPath" class="java.nio.file.Paths" factory-method="get">
<constructor-arg value="/my/path" />
<constructor-arg><array /></constructor-arg>
</bean>
Note:
class
attribute.array
constructor argument, to force selection of the correct overload of the factory method. This avoids having to go the round-about route of instead constructing a file URI.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With