Spring注解
accttodo 12/31/2023 SpringBoot
目录
参考:
# Spring注解
# @Lazy (opens new window)
作用:用于指示Spring容器延迟(懒加载)初始化被注解的Bean。。
应用场景:可用于性能优化、资源节省、解决循环依赖问题
引入版本:
# @PostConstruct (opens new window)
注解作用:作用在Servlet生命周期上,实现在Bean初始化之前自定义操作。
应用场景:主要是在Servlet初始化之前加载一些缓存数据,如:数据字典,读取properties配置文件等。
引入版本:Java5
# @ComponentScan 和 @Bean ?
在Spring框架中,@ComponentScan
和@Bean
都是用于组件注册的核心注解,但它们的用途和工作方式有所不同:
# 1. @ComponentScan
作用:用于自动扫描指定包路径下的组件类(如
@Component
、@Service
、@Controller
等注解标记的类),并将它们注册为Spring容器中的Bean。使用方式:
@Configuration @ComponentScan("com.example") // 扫描com.example包及其子包 public class AppConfig {}
1
2
3特点:
- 默认扫描当前配置类所在包及其子包。
- 可通过
basePackages
或basePackageClasses
属性指定扫描范围。
# 2. @Bean
作用:在配置类中显式声明一个Bean,通常用于第三方库的类或需要自定义初始化逻辑的场景。
使用方式:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
1
2
3
4
5
6
7特点:
- 作用于方法级别,方法返回的对象会被Spring容器管理。
- 可通过
name
或value
属性指定Bean的名称(默认使用方法名)。
# 主要区别
特性 | @ComponentScan | @Bean |
---|---|---|
作用级别 | 类/包级别(自动扫描) | 方法级别(显式声明) |
适用场景 | 扫描自有代码中的组件 | 注册第三方库类或复杂Bean |
自定义性 | 较弱(依赖组件注解) | 更强(可自定义初始化逻辑) |
典型用途 | 标记@Component 等注解的类 | 工厂方法或需要特殊配置的Bean |
# 常见组合使用
@Configuration
@ComponentScan("com.example") // 自动扫描
public class AppConfig {
@Bean // 手动注册
public DataSource dataSource() {
return new HikariDataSource();
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# @ComponentScan和@Component有何区别?
@ComponentScan
和@Component
是Spring框架中两个核心但功能不同的注解,主要区别如下:
# 1. 功能作用
**@Component** 用于标记类为Spring组件,表示该类需要被Spring容器管理。它是
@Controller
、@Service
、@Repository
的通用父注解,理论上可替代这些注解,但实际开发中建议按分层使用特定注解以提高代码可读性。@Component public class MyComponent {}
1
2**@ComponentScan** 用于配置类(如
@Configuration
类或启动类),指定Spring扫描哪些包路径下的组件(即被@Component
及其子注解标记的类)。@Configuration @ComponentScan("com.example") // 扫描com.example包及其子包 public class AppConfig {}
1
2
3
# 2. 使用场景
注解 | 适用场景 |
---|---|
@Component | 标记需要被Spring管理的类(如工具类、通用服务等)。 |
@ComponentScan | 在配置类中声明扫描范围,通常用于启动类或核心配置类。 |
# 3. 层级关系
@Component
是类级别注解,直接作用于需要注册的类。@ComponentScan
是配置级别注解,作用于配置类,控制组件的扫描范围。
# 4. 默认行为
- **@ComponentScan**:
- 若不指定包路径,默认扫描当前配置类所在包及其子包。
- 在Spring Boot中,
@SpringBootApplication
已包含@ComponentScan
,因此主启动类所在包及其子包会自动扫描。
- **@Component**: 需显式标记在类上,Spring不会自动识别未标记的类。
# 总结对比
特性 | @Component | @ComponentScan |
---|---|---|
作用目标 | 类(标记为Bean) | 配置类(指定扫描路径) |
功能 | 声明单个Bean | 批量扫描并注册Bean |
层级 | 元注解(父注解) | 配置注解(控制扫描范围) |
必要性 | 必须标记需管理的类 | 仅在需要自定义扫描路径时显式配置 |