【发布时间】:2021-10-11 00:50:21
【问题描述】:
我正在学习 Spring,同时我喜欢使用 @Component 和 @Autowired 让 Spring 管理依赖 bean 的想法。例如,我有一个可以使用的 Service 类和 Builder 类
// SomeService.java
@Service
public class SomeService {
// SomeBuilder is a @Component class
@Autowired
SomeBuilder someBuilder;
}
// SomeController.java
@Component
public class SomeController {
@Autowired
SomeService someSerivce;
}
Spring 会使用 @Autowired 处理从 SomeController 到 SomeService 到 SomeBuilder 的创建。但是,现在我的 SomeService 类需要一个私有字段,它不是 Component 类,只是一个普通的上下文对象,例如
// SomeService.java
@Service
public class SomeService {
@Autowired
SomeBuilder someBuilder;
private SomeContext someContext;
// Plan A: Using constructor to initiate the private field. However, I cannot use @Autowired to initiate SomeService in SomeController anymore as it requires a parameterless constructor
// Plan B: using @Autowired on constructor level, I cannot use this because SomeContext is not a @Component class
//public SomeService(SomeContext someContext) {
//this.someContext = someContext;
//}
// Plan C: This seems work but I kinda feel it's not the right way, as usually private field are initiated through constructor
//public void init(SomeContext someContext) {
// this.someContext = someContext;
//}
// demo usage of someContext
public someAnswer realMethod() {
System.out.println(someContext.getName());
}
}
现在我不知道如何注入 someContext,我用过
方案 A:使用类构造函数分配私有字段
计划 B:在构造函数级别使用 @Autowired
方案 C:使用有线方法分配私有字段。
但我不满意,也没有明确的方法来采取正确的方法。
【问题讨论】:
-
这就是构造函数的用途。使用它们而不是现场注入。 (在“我需要一个不是 bean 的值”的情况下,您可以使用
@Bean方法。) -
有什么可以参考的例子吗?我现在不是使用 Bean 注释的专家,你是建议将
@Bean放在我的init方法上还是其他地方? -
@Bean方法进入@Configuration类。您正在寻找的功能集在 3.0 中是新的时称为 JavaConfig,但现在只是配置 Spring 上下文的标准方法。 -
字段为
private这一事实并不意味着它必须通过构造函数进行初始化,这种思路是错误的。基本上你的所有字段都应该是private和@Autowired(你可能最好使用构造函数注入,因为这比隐藏字段更清晰)。为什么SomeContext不是一个bean?你对 bean 的定义是什么?在控制器中使用@Autowired并且没有无参数构造函数的另一件事彼此无关。
标签: java spring dependency-injection autowired