Equivalent to Provider of guice - FactoryBean in Spring.
From the documentation:
The FactoryBean interface is the capacity point in the Spring Logic of IoC container creation. If you have complex initialization code that is better expressed in Java rather than a (potentially) verbose amount of XML, you can create your own FactoryBean, write complex initialization inside this class, and then connect your custom FactoryBean to the container.
Example
public class MyFactoryBean implements FactoryBean<MyClassInterface> { @Override public MyClassInterface getObject() throws Exception { return new MyClassImplementation(); } @Override public Class<?> getObjectType() { return MyClassInterface.class; } @Override public boolean isSingleton() { return true; } }
This is a good approach when you have external libraries and complex object creation to avoid a long XML configuration for setting beans.
To use it in your context, you can simply present it as a regular bean in your XML context, for example:
... <bean id="myClass" class="foo.bar.MyFactoryBean" /> ...
BUT , if your bean is simple enough to instantiate (not many dependencies), you can configure it directly in the XML context, for example:
<bean id="myClass" class="foo.bar.MyClassImplementation" />
Alternative
If you are using Spring 3, you can write a configuration class (a class annotated with @Configuration ) as described here . With this approach, you can do something like:
@Configuration public class MyConfiguration { @Bean public MyClassInterface getMyClass() { return new MyClassImplementation(); } }
This will add your instance to the Spring context and allow it to auto-invert to other classes. But some configuration is required, and it is quite easy according to the provided documentation.