在Spring框架中,@Autowired注解是一个非常重要的注解,用于实现依赖注入(Dependency Injection, DI)。通过@Autowired注解,Spring容器可以自动将依赖的Bean注入到目标Bean中,从而简化代码并提高可维护性。
核心思想:不要自己"new"对象
在没有 Spring 的时候,如果 A 类需要 B 类,我们会这样写:
public class A {
private B b;
public A() {
this.b = new B(); // 自己创建依赖对象
}
}
问题:A 和 B 紧密耦合在一起,很难测试和维护。
@Autowired 的作用:让 Spring 帮你"找人"
使用 @Autowired 后:
@Component
public class A {
@Autowired
private B b; // Spring 会自动把 B 的实例注入进来
// 不需要自己 new B() 了!
}
@Component
public class B {
// B 也是一个由 Spring 管理的组件
}
生活中的比喻
把 Spring 容器想象成一个公司的 HR 部门:
-
@Component:就像员工入职登记
-
@Autowired:就像说"我需要一个助手",HR 会自动给你分配
18万+

被折叠的 条评论
为什么被折叠?



