javaspringannotationsstatic-factory

Spring 3 @Component and static factory method


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

Solution

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