← 返回首页
🌱

Spring框架入门:IoC与DI

📂 java ⏱ 2 min 300 words

Spring框架入门:IoC与DI

概述

Spring是Java企业级应用开发的主流框架。本教程介绍Spring的核心概念IoC(控制反转)和DI(依赖注入)。

1. IoC容器

import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

// 配置类
@Configuration
@ComponentScan("com.example")
public class AppConfig {
    
    @Bean
    public UserService userService() {
        return new UserService();
    }
}

// Bean定义
@Component
public class UserRepository {
    public User findById(Long id) {
        return new User(id, "Alice", 25);
    }
}

// 使用@Component注解
@Component
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public User getUser(Long id) {
        return userRepository.findById(id);
    }
}

// 启动容器
public class SpringDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);
        
        UserService userService = context.getBean(UserService.class);
        User user = userService.getUser(1L);
        System.out.println("用户: " + user);
        
        context.close();
    }
}

2. 依赖注入

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

// 构造器注入(推荐)
@Service
public class OrderService {
    private final UserService userService;
    private final PaymentService paymentService;
    
    @Autowired
    public OrderService(UserService userService, PaymentService paymentService) {
        this.userService = userService;
        this.paymentService = paymentService;
    }
    
    public void createOrder(Long userId, double amount) {
        User user = userService.getUser(userId);
        paymentService.processPayment(user, amount);
    }
}

// Setter注入
@Service
public class ReportService {
    private DataSource dataSource;
    
    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}

// 字段注入(不推荐)
@Service
public class NotificationService {
    @Autowired
    private EmailService emailService;
    
    @Autowired
    @Qualifier("smsService")
    private SmsService smsService;
}

3. Bean作用域

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

// 单例(默认)
@Component
@Scope("singleton")
public class SingletonBean {
}

// 原型
@Component
@Scope("prototype")
public class PrototypeBean {
}

// Web作用域
// Request:每次HTTP请求
// Session:每个会话
// Application:整个应用

4. 实际应用示例

配置管理

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    @Value("${app.name}")
    private String appName;
    
    @Value("${app.version}")
    private String appVersion;
    
    @Value("${database.url}")
    private String databaseUrl;
}

条件Bean

import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class ConditionalConfig {
    
    @Bean
    @Conditional(ProductionCondition.class)
    public DataSource productionDataSource() {
        return new ProductionDataSource();
    }
    
    @Bean
    @Conditional(DevelopmentCondition.class)
    public DataSource developmentDataSource() {
        return new DevelopmentDataSource();
    }
}

5. 最佳实践

  1. 使用构造器注入:保证依赖不可变
  2. 避免循环依赖:合理设计Bean依赖关系
  3. 使用接口编程:降低耦合度
  4. 合理配置Bean作用域:根据需求选择
  5. 使用Profile:区分环境配置

总结

Spring框架是Java企业级应用开发的主流框架。掌握IoC和DI的概念,可以编写松耦合、易维护的代码。