Spring应用程序上下文在构造函数中可用
当我尝试在 spring 使用构造函数参数实例化的 bean 内从 spring 应用程序上下文创建 bean 时遇到问题。
我已经实现了 ApplicationContextAware 接口,但它在创建实例后填充上下文(显而易见)。
但是,如果您需要从构造函数获取 bean,并且我正在谈论在运行时定义的可变数量的对象,那么正确的处理方法是什么?
I am having an issue when trying to create beans from a spring Application Context inside a bean instantiated by spring using constructor arguments.
I have implemented the ApplicationContextAware
interface but it populates the context after the instance is created (obvious).
But then, if you need to get beans from the constructor, and I am talking about a variable number of objects defined at runtime, what would be the correct way to proceed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在Spring实例化的bean中,不是在构造函数中初始化它,而是在专用方法中初始化它,对于Spring来说标记为“init-method”。
您的效果与在构造函数中初始化的效果大致相同,但您使用的是正确的 Spring 生命周期。
In beans instanciated by Spring, instead of initializing it in the Constructor, initialize it in a dedicated method, marked as "init-method" for Spring.
You have about the same effect as initializing in the constructor, but you are using the correct Spring life-cycle.
您可以利用面向方面的编程从构造函数中访问上下文。 Spring 对此有特殊支持 - @Configurable(preConstruction = true)。
请随意在 spring 参考中阅读更多相关内容 - 6.8.1。使用AspectJ通过Spring依赖注入域对象
You can make the context accessible from constructor exploiting aspect-oriented programming. Spring has special support for that - @Configurable(preConstruction = true).
Feel free to read more about that at the spring reference - 6.8.1. Using AspectJ to dependency inject domain objects with Spring