 闽公网安备 35020302035485号
                
                闽公网安备 35020302035485号
                控制反转(IoC):将对象创建和管理的责任交给 Spring,降低了系统的复杂性。
	
import org.springframework.stereotype.Component;
@Component
public class MyService {
    public void sayHello() {
        System.out.println("Hello, Spring Boot!");
    }
}
在这个例子中,@Component 注解表示MyService 类是一个 Spring Bean。import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
    
    @Bean
    public MyService myService() {
        return new MyService();
    }
}
在这个示例中,AppConfig 类通过@Bean 注解定义了一个MyService Bean,Spring 会自动将其注册到容器中。@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
三. Spring Bean 的生命周期销毁:当容器销毁时,执行销毁方法(如实现DisposableBean 接口或使用@PreDestroy 注解)。
	
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class MyService {
    
    @PostConstruct
    public void init() {
        System.out.println("Bean 初始化");
    }
    @PreDestroy
    public void destroy() {
        System.out.println("Bean 销毁");
    }
}
在这个示例中,@PostConstruct 和@PreDestroy 注解分别用于指定 Bean 初始化和销毁时的回调方法。import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
    
    private final MyRepository myRepository;
    
    @Autowired
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }
}
字段注入@Component
public class MyService {
    @Autowired
    private MyRepository myRepository;
}
Setter 注入@Component
public class MyService {
    
    private MyRepository myRepository;
    
    @Autowired
    public void setMyRepository(MyRepository myRepository) {
        this.myRepository = myRepository;
    }
}
五. Spring Bean 的作用域Session:每个 HTTP 会话创建一个新的 Bean 实例(仅适用于 Web 应用)。
	
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class MyService {
    public MyService() {
        System.out.println("MyService 实例化");
        System.out.println("堆代码 duidaima.com");
    }
}
六. 常见问题与调试技巧