Spring学习-Spring IoC容器
一.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 延迟创建(调用时再创建),其生命周期的覆盖的范围如下:
本文章整理自上课PPT,仅供学习使用。
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
如何跳出当前的多重嵌套循环?