文章目录
Spring是什么
Spring是一个包含众多工具的IoC容器
容器
- list/map 装数据的容器
- tomcat 装web的容器
Spring容器装的是对象
Ioc 详解
Ioc是控制反转
控制权反转,创建对象的控制权反转了,交给了Spring。
注解就是控制反转的应用。
Bean的存储
把对象交给IoC容器管理需要在类上加一个注解:@Component,Spring为了更好的服务Web开发,还提供了其他的注解。
类注解:
@Controller
(控制存储器)
@Service
(服务存储)
@Repository
(仓库存储)
@Component
(组件存储)
@Configuration
(配置存储)
方法注解:
@Bean
@Controller(控制存储器)
使⽤ @Controller 存储 bean :
@Controller // 将对象存储到 Spring 中
public class UserController {
public void doController(){
System.out.println("do Controller...");
}
}
观察这个对象是否已经存在Spring容器当中:
Spring上下文
//Spring上下文
ApplicationContext context = (ApplicationContext) SpringApplication.run(DemoApplication.class, args);
返回的就是Spring的运行环境。
从Spring容器中获取对象:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//获取Spring上下⽂对象
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
//从Spring上下⽂中获取对象
UserController bean = context.getBean(UserController.class);
//使⽤对象
bean.doController