spring-boot - 在spring boot中导入其他类和使用@autowired有什么区别?
问题描述
在 ClassA 的 Spring Boot 中,我们可以通过导入 ClassB 类来获取 ClassB 方法,这与我们对 @autowired 所做的行为相同。那么这两者之间的主要区别是什么。
解决方案
import
,顾名思义,就是 导入依赖。@Autowired
创建该依赖项的实例并将其注入到我们的component
.
假设我们有某个 B 类,例如:
class B {
public B() {}
public void sayHi() {
System.out.println("Hello World");
}
}
进口
import ClassB;
class A {
private B bRef;
public A() {}
public void sayHi() {
bRef.sayHi();
}
public static void main(String[] args) {
A a = new A();
a.sayHi(); // NullPointerException -> we bRef is null
}
}
@自动连线
import ClassB;
@Component
class A {
// autowiring member variables is considered bad but just to
// illustrate the point
@Autowired
private B bRef;
public A() {}
public void sayHi() {
bRef.sayHi();
}
public static void main(String[] args) {
A a = new A();
a.sayHi(); // Outputs: Hello World
// bRef was constructed and injected into our component
}
}
推荐阅读
- google-cloud-platform - 更改 GKE 集群的 CIDR 子网
- mysql - SQL 查询计算并显示过去 12 个月的每个月的总和数据
- arrays - Excel VBA - 将数组添加到字典并搜索它是否存在
- javascript - 为什么我的网站在每个文件都成功加载后显示加载图标?
- acumatica - 为什么这个错误会在 acumatica 中刷新页面。{“消息”:“发生错误。”}
- reactjs - 在 Django 中生成可共享的链接功能?
- django - 获取与 django 模型数组字段相关的错误
- timer - 如何停止启动时设置的定时器?
- python - Python 在单个循环中将 Json 数组转换为 Excell 文件
- flutter - 无法使用静态访问访问实例成员“项目”