在实践中进行依赖注入
学习使用 `@Autowired` 和构造函数注入来管理应用程序中的依赖项。
在实践中进行依赖注入 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
DI in Practice: Intro
Welcome to Dependency Injection in Practice! In Spring Boot, we don't manually create objects. Instead, Spring handles this for us, 'injecting' what an object needs.
This lesson focuses on the two primary ways to ask Spring to inject dependencies into your components: Field Injection and Constructor Injection.
What's a Dependency?
Think of dependencies as the 'ingredients' an object needs to do its job. For example, a CoffeeMaker might need a WaterHeater and a CoffeeBeanGrinder.
- Dependency: An object that another object relies on.
- Injection: Spring providing these required objects automatically.
This keeps your code cleaner and easier to test!
Field Injection with @Autowired
Field injection is the simplest way to tell Spring to inject a dependency. You place the @Autowired annotation directly above the field that needs the dependency.
Spring will then find a suitable bean (an object managed by Spring's IoC container) and assign it to that field.
Field Injection Example
Let's see field injection in action. Here, MyService needs an instance of MyComponent.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
class MyComponent {
public String greet() {
return "Hello from Component!";
}
}
@Component
class MyService {
@Autowired
private MyComponent component;
public void performAction() {
System.out.println(component.greet());
}
}
public class Main {
public static void main(String[] args) {
// In a real Spring app, Spring manages this.
// For this example, we simulate it.
MyComponent comp = new MyComponent();
MyService service = new MyService();
// Simulate injection (Spring does this automatically)
service.component = comp;
service.performAction();
}
}Field Injection: The Downsides
While easy, field injection has some drawbacks:
- Testing: It's harder to unit test components without a Spring context because you can't easily pass mock dependencies.
- Immutability: Fields can't be declared
final, making objects mutable after creation. - Tight Coupling: It obscures the object's dependencies, making it less clear what it needs.
Most Spring developers prefer an alternative...
Constructor Injection: The Preferred Way
Constructor injection is generally considered the best practice for dependency injection. Here, dependencies are provided as arguments to the class's constructor.
This makes dependencies explicit and ensures that an object is fully initialized and valid upon creation.
Constructor Injection Example
Notice how MyService now requires MyComponent as a constructor argument. Spring automatically provides it!
import org.springframework.stereotype.Component;
@Component
class MyComponent {
public String greet() {
return "Hello from Component!";
}
}
@Component
class MyService {
private final MyComponent component;
// Spring automatically injects MyComponent here
public MyService(MyComponent component) {
this.component = component;
}
public void performAction() {
System.out.println(component.greet());
}
}
public class Main {
public static void main(String[] args) {
// In a real Spring app, Spring manages this.
// For this example, we simulate it.
MyComponent comp = new MyComponent();
MyService service = new MyService(comp); // Manual injection for demo
service.performAction();
}
}@Autowired on Constructor?
When a class has only one constructor, Spring 4.3+ automatically treats it as a constructor for dependency injection. You don't need to add @Autowired explicitly.
If there are multiple constructors, you would use @Autowired on the specific constructor you want Spring to use for injection.
Which Injection Type to Choose?
Here's a quick guide:
- Constructor Injection: Recommended for most cases. Promotes immutability, easier testing, and clear dependencies.
- Field Injection: Avoid if possible. Can be used for optional dependencies or in very specific legacy scenarios.
- Setter Injection: Useful for optional dependencies that might change during the object's lifecycle. Less common than constructor injection.
Test Your Knowledge!
Which statement best describes the primary benefit of Constructor Injection over Field Injection in Spring Boot?
Recap: DI in Practice
You've learned about practical dependency injection in Spring Boot!
- Field Injection uses
@Autowireddirectly on fields, but has drawbacks. - Constructor Injection is the preferred method, making dependencies explicit and promoting immutability.
- Spring automatically handles constructor injection for single constructors.
Using the right injection type leads to more robust and testable applications. Next, we'll look at externalizing application properties!
常见问题解答
「在实践中进行依赖注入」课时是免费的吗?
是的 — 「在实践中进行依赖注入」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
「在实践中进行依赖注入」这节课中我会学到什么?
学习使用 `@Autowired` 和构造函数注入来管理应用程序中的依赖项。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Complete Guide 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「在实践中进行依赖注入」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?
能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 了解 Spring IoC 容器
- 在实践中进行依赖注入
- 外部化应用程序属性
- Bean 作用域与生命周期管理