Spring 3 @Component and static factory method

shrini1000 picture shrini1000 · Mar 7, 2012 · Viewed 15.6k times · Source

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
    }
}

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Mar 7, 2012

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.