一.Spring IoC 介绍
IoC(Inversion of Control):控制反转
Java 实例的生命周期,原先由程序员自行手动管理,转交给Spring容器进行自动化的管理
DI(Dependency Injection):依赖注入
当一个类A的实例中需要依赖类B的实例,而B的实例中又需要依赖类C的实例,如此往复,从而实现将不同类之间的相互依赖进行构建的过程,叫做依赖注入。
DI 是 IoC 的具体实现方式:
手动设置对象关联:
通过IoC容器管理对象关联:
实践工程层面,对象之间还存在生命周期上的差异
传统方式管理:
手动实例化对象/通过工厂方法管理
通过 IoC 容器管理:
依赖对象的生命周期可控
二.Spring属性注入的三种方式
依赖注入(主要)
public class DemoController{
@Resource
private DemoService demoService;
}
构造方法注入(次要)
public class DemoController{
private DemoService demoService;
@Autowired
public DemoController(DemoService demoService){
this.demoService = demoService;
}
}
Setter方法注入(次要)
public class DemoController{
private DemoService demoService;
@Autowired
public void setService(DemoService demoService){
this.demoService = demoService;
}
}
三.Spring 多实例注入
可以针对一个接口创建的多个实现类注入到集合字段中。
@Component
public class MyDemoServiceImpl implements DemoService{
}
@Component
public class YourDemoServiceImpl implements DemoService{
}
public class DemoController{
@Autowired
private Set<DemoService> demoServices;
}
多实例的优先级排序:@Primary,@Priority(n),@Order(n),Ordered(n 的值越小优先级越高)。
四.Spring 创建对象的常用方式
方法1:注解式
@Component
public class DemoService{
public String sayHello(String name){
return "hello" + name;
}
}
关键注解:@Component/@Service/@Repository
方法2:工厂式
@Configuration
public class Config{
@Bean
public DemoService demoService(){
return new DemoService();
}
}
关键注解:@Configuration + @Bean
五.Spring 手动从容器中获取对象
通过在 Spring 托管对象中注入 Spring 容器类 ApplicationContext,再调用 getBean 系列方法获取对象
@RestController
public class DemoController{
@Resource
private ApplicationContext applicationContext;
@GetMapping("/hello")
public String sayHello(String name){
DemoService demoService = applicationContext.getBean(DemoService.class);
return demoService.sayHello(name);
}
}
注意:
- Spring 的容器 ApplicationContext 本身是可以注入到被 Spring 托管的对象中的
- getBean 可以按照名字(String)的方式获取,也可以按照类(Class)的方式获取,甚至可以按照两者同时指定获取
- 除了getBean还有getBeansOfType,批量获取一批同一类(Class)的多个不同实例对象
六.Spring 托管对象的生命周期
Spring 托管对象支持 @Lazy 延迟创建(调用时再创建),其生命周期的覆盖的范围如下:
取值范围 | 说明 |
Singleton(默认) | 容器中只有一个实例,当容器启动或者被第一次使用时初始化,即使是在多线程不同宿主的环境下,也都是拥有并共享同一个实例。只要服务不停止,单例对象就不会主动消亡 |
Prototype | 容器中拥有多个实例,从而被不同的宿主对象拥有,可以从容器中反复创建并获取。每次获取后可能随着宿主环境消亡 |
本文章整理自上课PPT,仅供学习使用。