文章目录
学习Spring源码的注意点
- 学习Spring源码的注意点
- 基于注解加载Bean
- 验证Controller等其他注解加载进容器
- 不要太在意版本的问题
- 不用太过于在意细节, 掌握主要流程为主
在之前的如下文章中, 是根据xml去加载Bean 的 https://javaweixin6.blog.csdn.net/article/details/113790554 本次改为根据注解把bean加载到容器中去 在Service的实现类中, 加上@Service
注解 Entrance类改造成为一个配置类.
Entrance类如下
- 使用
@Configuration
注解标明是一个配置类 - 使用
@ComponentScan
标明要扫描的包路径 - 使用
new AnnotationConfigApplicationContext(Entrance.class)
来标明是注解配置, 并且传入配置类来启动容器和加载bean 到容器中
启动容器后, 便可以获取所有已经加载的bean的名称, 以及通过bean 的名称调用getBean方法去获取bean.
// 配置类的标识, 作用类似于xml文件
@Configuration
// 扫描的包路径, 把指定路径的类放入Spring容器中
@ComponentScan("com.demo")
public class Entrance {
public static void main(String[] args) {
// 启动容器 ,并且根据注解扫描和加载bean到容器中
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Entrance.class);
//获取容器中所有的bean的名称
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
// 遍历所有bean的名称
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println("获取bean 的名称 : " +beanDefinitionName);
}
WelcomeService welcomeService = (WelcomeService) applicationContext.getBean("welcomeServiceImpl");
welcomeService.sayHello(" 你好Spring");
}
}
运行main方法后, 打印如下, 可以看到成功加载了bean , 并且也通过getBean方法获取到了实例和调用了其成员方法.
创建一个Controller, 使用@Controller
注解, 并且用@Autowired
来注入Service. handleRequest 方法中, 使用Service去调用方法.
package com.demo.controller;
import com.demo.service.WelcomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/**
* @author: https://javaweixin6.blog.csdn.net/
* 创建时间:2021/3/10 7:21
* Version 1.0
*/
@Controller
public class WelcomeController {
@Autowired
private WelcomeService welcomeService;
public void handleRequest() {
welcomeService.sayHello(" controller调用了Service ");
}
}
使用Dao
@Repository
public class WelcomeDaoImpl implements WelcomeDao {
}
测试: 从容器中获取WelcomeController , 并且调用handleRequest方法
public static void main(String[] args) {
// 启动容器 ,并且根据注解扫描和加载bean到容器中
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Entrance.class);
//获取容器中所有的bean的名称
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
// 遍历所有bean的名称
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println("获取bean 的名称 : " + beanDefinitionName);
}
WelcomeController welcomeController = (WelcomeController) applicationContext.getBean("welcomeController");
welcomeController.handleRequest();
}
程序运行后可以看到获取了如下的bean , 并且成功调用了方法. 通过上面的一些例子可以看到, Spring IOC主流程如下
- 解析配置
- 定位与注册对象
- 注入对象