第四章 SpringBoot v1.0
第一部分 SpringBoot原理
一、Bean管理
默认情况下,Spring项目启动时,会把bean都创建好放在IOC容器中.
1.获取Bean
- 根据name获取Bean:
Object getBean(String name) - 根据类型获取Bean:
<T> T getBean(class<T> requiredType) - 根据name和类型获取:
<T> T getBean(String name, class<T> requiredType)
java
@Autowired
private ApplicationContext applicationContext; //IOC容器对象
public void test() {
Controller bean = applicationContext.getBean("controller", Controller.class);
}2.Bean作用域

b.声明作用域
可以通过使用@Scope注解来进行配置作用域
java
@Scope("prototype")
@Controller
public class Controller {}c.延迟初始化
默认singleton的bean,在容器启动时被创建,可以使用@Lazy注解来延迟初始化到第一次使用时再进行
3.第三方Bean
a.@Bean
Bean对象来自于第三方(非自定义),无法用@Component及衍生注解声明bean的,就需要用到@Bean注解
b.@Configuration
若要管理的第三方Bean对象,可以对这些Bean进行集中分类配置,通过@Configuration注解声明一个配置类
java
@Configuration //自动配置类
public class ServiceConfiguration {
@Bean //将此方法返回的对象交由IOC容器管理,称为IOC容器的Bean对象
public InventoryService inventoryService() {
return new InventoryService();
}
}c.Bean的名称
Bean的名称默认为方法名,可以通过@Bean注解的value或name属性指定Bean的名称
d.@Component和@Bean使用场景
- 项目中自定义的,使用
@Component及其衍生注解 - 项目中引入第三方的,使用
@Bean注解
二、起步依赖与自动配置
1.基本原理
起步依赖原理:Maven依赖传递
自动配置:当spring容器启动后,一些配置类、bean对象就自动存入到了IOC容器中,不需要手动声明
2.导入配置
方案一:@ComponentScan扫描
java
@ComponentScan({"com.example","com.hymsk"})
@SpringBootApplication
public class SpringbootApplication {}方案二:@Import导入
- 导入普通类:
@Import({MyClass.class}) - 导入配置类:
@Import({MyConfig.class}) - 导入
ImportSelector实现类:@Import({MyImportSelector.class})
java
public class My ImportSelector implements ImportSelector {
public String[] ImportSelects(AnnotationMetadata importingClassMetadata) {
return new String[] {"com.example.HeaderConfig", ...};
}
}- 定义
@EnableXxxx注解,用于封装@Import注解(SpringBoot采用)
java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(ImportSelector.class) //在该接口上使用了@ImportSelector注解
public @interface EnableConfig {}3.条件装配(@Conditional)
按照一定的条件进行判断,在满足给定条件后才会注册对应的bean对象到Spring IOC容器中
常见子注解:
@ConditionalOnClass(name="全类名"):
判断环境中是否有对应字节码文件,有则注册Bean到IOC容器
@ConditionalOnMissingBean([value="类型", name="名称"]):
判断环境中是否没有对应/指定Bean,没有则注册Bean到IOC容器(一般用于声明默认Bean)
@ConditionalOnProperty(name="name", havingValue="value"):
判断在配置文件中是否有对应的属性和值,有则注册Bean到IOC容器
4.自动配置原理
