If I'm writing a static factory method to create objects, how do I use the '@Component' annotation for that factory class and indicate (with some annotation) the static factory method which should be called to create beans of that class? Following is the pseudo-code of what I mean:
@Component
class MyStaticFactory
{
@<some-annotation>
public static MyObject getObject()
{
// code to create/return the instance
}
}
I am afraid you can't do this currently. However it is pretty simple with Java Configuration:
@Configuration
public class Conf {
@Bean
public MyObject myObject() {
return MyStaticFactory.getObject()
}
}
In this case MyStaticFactory does not require any Spring annotations. And of course you can use good ol' XML instead.
You need to use the spring interface FactoryBean.
Interface to be implemented by objects used within a
BeanFactorywhich are themselves factories. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.
Implement the interface and declare a bean for it. For example :
@Component
class MyStaticFactoryFactoryBean implements FactoryBean<MyStaticFactory>
{
public MyStaticFactory getObject()
MyStaticFactory.getObject();
}
public Class<?> getObjectType() {
return MyStaticFactory.class;
}
public boolean isSingleton() {
return true;
}
}
Through @Component and component scanning, this class will be discovered. Spring will detect that it is a FactoryBean and expose the object you return from getObject as a bean (singleton if you specify it).
Alternatively, you can provide a @Bean or <bean> declaration for this FactoryBean class.
Bean:
public class MyObject {
private String a;
public MyObject(String a) {
this.a = a;
}
@Override
public String toString() {
return a;
}
}
FactoryBean:
@Component
public class MyStaticFactory implements FactoryBean<MyObject> {
@Override
public MyObject getObject() throws Exception {
return new MyObject("StaticFactory");
}
@Override
public Class<?> getObjectType() {
return MyObject.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
Use:
@Component
public class SomeClass{
@Autowired
MyObject myObject;
}
来源:https://stackoverflow.com/questions/9598829/spring-3-component-and-static-factory-method