Dependency injection in Spring. not convenient regarding to prototype scope

Spring's DI works fine for singleton scope bean. However, regarding to prototype scope it is not convenient if the prototype bean itself will inject other beans. The thing is for prototype bean, I would like to create them using new keyword of Java with runtime constructor arguments which is hard to be statically described in XML bean configuration. Using new keyword makes the prototype bean out of Spring container, it is impossible to use Spring DI in them of course.

I am wondering how people solve problem like this? Of course I can use AspectJ to do myself injection as a compensation. But having two injection mechanisms is not an elegant solution to me.


@Configurable标记你的原型bean


You should be able to create prototype objects through context.getBean(name) or context.getBean(class) where context is ApplicationContext instance.

Another, perhaps even more convenient way is to use factory pattern with factory object being a singleton with all dependencies wired in and passing them to the constructed objects in factory.createInstance(...) .


Spring allows for passing constructor values to the getBean() method, check out this SO-Post:

spring bean with dynamic constructor value

Furthermore, what would be wrong about retrieving a bean from the context, that is just partially initialized and you are setting the runtime-parameters yourself via setters?

Be aware, that Spring-Beans are by default Singletons, so in your Spring-Config you would have to explicitely specify them as being prototype-scoped!

链接地址: http://www.djcxy.com/p/22684.html

上一篇: 如何为需要MyClass.class参数的工厂方法注入Spring Bean

下一篇: Spring中的依赖注入。 关于原型范围不方便