I was trying to create Hibernate Validator bean, and run into this problem creating a bean from static factory method in another Class. I found a Spring way to get my Validator bean initialized (solution at the bottom), but the problem itself remains unsolved. Validator is used as example case here.
This is how I create the Validator instance in Java
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
<bean id="validation" class="javax.validation.Validation" />
"Check that a method with the specified name exists and that it is non-static"
factory-method should only contain the method name, not including the class name.
If you want to use a static factory, give the
class of the factory(!) to the bean declaration, if you want to use an instance factory, give the
factory-bean to the bean declaration, but don't give both: The class of the created bean is not given in the bean declaration.
So a full example should look like this, using a static factory for
validatorFactory and an instance factory for
<bean id="validatorFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" /> <bean id="validator" factory-bean="validatorFactory" factory-method="getValidator" />
See details on the documentation:
To answer you question - How would you create bean in this kind of a situation in Spring? - Do it exactly as shown here, or if you can, use a utility class like the
LocalValidatorFactoryBean, which simplifies the Spring configuration.