一、IoC容器与依赖注入核心概念
控制反转(IoC)是Spring框架的核心思想,依赖注入(DI)是其具体实现方式。IoC容器通过注入对象依赖关系而非硬编码创建,实现了组件间的解耦。Spring提供三种主要配置方式:传统XML配置、便捷的注解配置和类型安全的Java配置。
二、三种注入方式深度分析
构造器注入:通过构造函数传递依赖,保证依赖不可变且完全初始化。Spring官方推荐的方式,特别适合必需依赖。
@Component
public class OrderService {
private final PaymentProcessor processor;
@Autowired
public OrderService(PaymentProcessor processor) {
this.processor = processor;
}
}
Setter注入:通过setter方法设置依赖,提供灵活性,适合可选依赖。
@Component
public class UserService {
private NotificationService notifier;
@Autowired
public void setNotifier(NotificationService notifier) {
this.notifier = notifier;
}
}
字段注入:直接注入字段,简洁但隐藏依赖关系,不利于测试。
@Component
public class ProductService {
@Autowired
private InventoryRepository repository;
}
三、三种配置方式示例
XML配置:传统方式,集中管理依赖关系
<bean id="userService" class="com.example.UserService">
<constructor-arg ref="notificationService"/>
</bean>
<bean id="notificationService" class="com.example.NotificationService"/>
注解配置:现代Spring应用主流方式
@Configuration
@ComponentScan("com.example")
public class AppConfig {
@Bean
public DataSource dataSource() {
return new DriverManagerDataSource(url, user, password);
}
}
Java配置:类型安全且功能强大
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class WebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
四、最佳实践与选择建议
对于必需依赖,推荐使用构造器注入;可选依赖使用Setter注入;而字段注入应谨慎使用。现代Spring开发中,建议以Java配置为主,注解配置为辅,XML配置仅用于遗留系统维护。
通过合理运用IoC容器的依赖注入特性,可以大幅提升代码的可测试性、可维护性和扩展性,真正实现面向接口编程和松耦合架构。
297

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



