Is it possible to dynamically instantiate a bean in Spring using a factory?
I'd like to be able to instantiate some beans when a particular annotation is detected.
E.g.
@Retention ( RetentionPolicy.RUNTIME)
@Target (ElementType.TYPE)
@Import(CreateFooRegistrar.class)
public @interface CreateFoo {
String name();
}
public interface Foo {
String getName();
void setName(String name);
}
public class FooImpl implements Foo {
...
}
I can easily create beans directly using the concrete class:
public class CreateFooRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(CreateFoo.class.getName()));
String fooName = attributes.getString("name");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FooImpl.class);
builder.addPropertyValue("name", fooName);
registry.registerBeanDefinition(fooName + "Foo", builder.getBeanDefinition());
}
}
But is there any way I can create a bean using the returned object from a factory?
E.g.
public class FooFactory {
public static FooImpl create(String name) {
FooImpl foo = new FooImpl();
foo.setName(name);
return foo;
}
}
The reason I ask is that all the beans I want to automatically create are typically instantiate via a factory. I don't own the factory code, so I'd prefer not to attempt to mimic its inner-workings myself.