商城网站建设php高端企业网站建站
Spring容器从启动到关闭的注解使用顺序及说明
1. 容器启动阶段
注解:@Configuration、@ComponentScan
作用:
@Configuration:标记配置类,声明Spring应用上下文的配置源。@ComponentScan:扫描指定包下的组件(Bean),自动注册为Spring管理的Bean。
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {// 配置类内容
}
2. Bean定义与发现阶段
注解:@Component、@Service、@Repository、@Controller
作用:
- 标记类为Spring管理的Bean,触发组件扫描机制将其注册到容器中。
@Service
public class MyService {// Service层Bean
}@Repository
public class UserRepository {// 数据库访问层Bean
}
3. 作用域与Bean配置阶段
注解:@Scope、@Lazy
作用:
@Scope:定义Bean的作用域(如prototype、request等,默认singleton)。@Lazy:延迟初始化Bean(在首次使用时创建,而非容器启动时)。
@Scope("prototype")
@Lazy
public class LazyBean {// 原型作用域且延迟初始化的Bean
}
4. 依赖注入阶段
注解:@Autowired、@Qualifier、@Value
作用:
@Autowired:自动注入依赖的Bean。@Qualifier:解决多Bean同类型时的歧义。@Value:注入配置属性(如application.properties中的值)。
@Service
public class MyService {@Autowired@Qualifier("primaryUserDao")private UserDao userDao;@Value("${app.config.timeout}")private int timeout;
}
5. 初始化阶段
注解:@PostConstruct
作用:
- 标记方法在依赖注入完成后执行,用于初始化逻辑(如数据预加载)。
@Service
public class MyService {@PostConstructpublic void init() {System.out.println("Bean initialized");}
}
6. 容器关闭阶段
注解:@PreDestroy
作用:
- 标记方法在容器关闭时执行,用于资源释放(如关闭连接、清理缓存)。
@Service
public class MyService {@PreDestroypublic void cleanup() {System.out.println("Bean destroyed");}
}
完整生命周期注解使用顺序表
| 阶段 | 注解 | 作用 |
|---|---|---|
| 容器启动 | @Configuration, @ComponentScan | 定义配置类并扫描组件,初始化容器 |
| Bean定义 | @Component, @Service, etc. | 标记类为Spring管理的Bean |
| 作用域与配置 | @Scope, @Lazy | 定义Bean的作用域和初始化时机 |
| 依赖注入 | @Autowired, @Qualifier, @Value | 自动注入依赖、解决歧义、注入配置属性 |
| Bean初始化 | @PostConstruct | 在依赖注入后执行初始化逻辑 |
| 容器关闭 | @PreDestroy | 在容器关闭前执行资源清理 |
关键说明
-
顺序依赖:
@Configuration和@ComponentScan是容器启动的前提条件,必须先定义配置类和扫描路径。@PostConstruct必须在依赖注入完成后执行,而@PreDestroy必须在Bean销毁前执行。
-
扩展注解:
@Primary:在存在多个同类型Bean时,指定默认注入的Bean(需与@Autowired配合)。@Profile:按环境(如dev、prod)选择性注册Bean。@Bean:在配置类中显式定义Bean(需结合@Configuration使用)。
总结
Spring容器从启动到关闭的注解使用顺序为:
@Configuration → @ComponentScan → @Component/Service/... → @Scope/@Lazy → @Autowired/@Qualifier/@Value → @PostConstruct → @PreDestroy。
通过这些注解,可以清晰地控制Bean的生命周期、依赖关系和作用域,实现灵活的Spring应用管理。
