【发布时间】:2017-08-09 14:51:24
【问题描述】:
我有一个配置了构造函数的旧类
public class Outer
{
...
public Outer(OldService oldService) { this.oldService = oldService;}
}
我需要使用新服务添加新字段,但无法更改构造函数(太多旧代码依赖它)。所以,我想得到类似的东西
public class Outer
{
private NewService newService; // Need injection here
public Outer(OldService oldService) { this.oldService = oldService;}
}
@Component
public class NewService
{
public NewService(Dependency dependency){this.dependency = dependency;}
}
我尝试为 Outer.newService 应用 @Autowired 和 @Inject 属性,但没有帮助。我可以创建 Outer.Initiate(NewService newService) 方法,但这会给已经闻到的项目添加一些垃圾。
那么,我可以在 Spring 中注入字段吗?
Upd1 现在手动执行外部构造函数(如 var outer = new outer(service);)。
【问题讨论】:
-
如果你有很多遗留代码直接调用旧的构造函数,你希望遗留代码如何填充
newService字段? -
您的
Outer类需要是 Spring 组件。否则,自动装配将不起作用。 -
如果你想要一个新的必需的
NewService,你不会也破坏你的旧代码。为什么不使用构造函数(OldService oldService, NewService newService) { super(oldService); }扩展类Outer像NewOuter? -
@Juan 我已经尝试为字段应用 Autowired,为类应用组件 - newService 为空。约翰,我想即使手动调用构造函数,Spring DI 容器也会填充 newService。我错了吗?
-
不,它不会那样工作,因为您正在创建一个实例而不是使用 Spring Bean。您应该像这样创建一个
@Bean:@Bean public Outer outer(){ return new Outer(oldService); }然后您可以使用@Autowired 来获取该bean,其余的由Spring 完成。