Spring 3 @Component and static factory method

You need to use the spring interface FactoryBean.

Interface to be implemented by objects used within a BeanFactory which 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.


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.