Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Path bean

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.
  • The static factory method also has an overloaded variant, 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()'."

like image 773
Raedwald Avatar asked Jun 17 '14 11:06

Raedwald


People also ask

How do I create a custom bean in Spring boot?

Different Methods to Create a Spring BeanCreating Bean Inside an XML Configuration File (beans. xml) Using @Component Annotation. Using @Bean Annotation.

Can we use @bean without @configuration?

@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.

What is the @bean annotation?

@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 .


1 Answers

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:

  • Give the name of the factory class, rather than the object class, as the value of the class attribute.
  • Give an extra empty 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.
like image 137
4 revs, 2 users 91% Avatar answered Oct 02 '22 01:10

4 revs, 2 users 91%