I do not see a problem with the factory bean, and I would do it like this:
import org.springframework.beans.factory.FactoryBean; import org.springframework.stereotype.Component; @Component public class X { public static class XFactory implements FactoryBean<X> { @Override public X getObject() throws Exception { return new X(); } @Override public Class<?> getObjectType() { return X.class; } @Override public boolean isSingleton() { return false; } } }
and enter this factory bean.
Otherwise, you can host your X bean with
@Scope(proxyMode=ScopedProxyMode.TARGET_CLASS, value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
You must use the default proxy mode so that spring creates a proxy server that always returns a new instance to your singleton.
If you are using XML configuration than this:
<bean id="x" class="X" scope="prototype"> <aop:scoped-proxy> </bean>
Good luck.
Edit:
When you comment your factory via @Component (I added it above), return false to #isSingleton and make sure you don't return your X twice, you can enter the factory bean with @ Got it in your singleton.
Otherwise, I just checked
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Component @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS) public class X { }
works as expected.
Edit 2:
If you donβt want to enter a factory bean but just want to add a dependency, you can prototype the area of ββyour factory (@Scope (proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")) but a new factory is created every time X is involved, which, probably not what you want.
If you do not want to enter factory yourself, I would go with the Olivers search method.