Spring注入一个使用静态方法调用的实例创建的对象
我创建了一个对象,如下所示:
serviceValidatorObject = ServiceFactory.getInstance().getServiceValidator()
该对象是通过调用静态方法 getInstance()
,然后调用实例方法 getServiceValidator()
创建的。
我想使用 Spring 注入来配置它。
问题是 ServiceFactory 是我无法更改的遗留代码。
我知道 Spring 支持通过工厂类静态或实例方法进行注入,但是我是否可以在 Spring 中配置上面的对象创建?
I have an object created as follows:
serviceValidatorObject = ServiceFactory.getInstance().getServiceValidator()
The object is created from a call to static method, getInstance()
, then an instance method, getServiceValidator()
.
I want to use Spring injection to configure this instead.
The trouble is the ServiceFactory is legacy code that I cannot change.
I know Spring supports injection through a factory class static or instance method, but is there anyway I can configure the object creation above in Spring?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的例子中,exampleBean 是您的
serviceValidatorObject
,factory-bean 是serviceFactory
,工厂方法是getServiceValidator
。你可能也需要这个:In your case, exampleBean is your
serviceValidatorObject
, factory-bean isserviceFactory
, and the factory-method isgetServiceValidator
. You might need this, too:您可以使用这个 bean 定义:
You could use this bean definition:
您应该能够使用以下方法实现此目的:
然后您可以使用 @Resource 或 @Autowired + @Qualifier 直接注入到您的对象中。
对于此示例,您的 applicationContext.xml 应包含:
然后您可以通过以下方式注入到您的代码中:
You should be able to achieve this using:
Then you can use either @Resource or @Autowired + @Qualifier to inject into your object directly.
For this example, your applicationContext.xml should contain:
And then you could inject into your code via: