您当前的位置: 首页 >  spring

java持续实践

暂无认证

  • 4浏览

    0关注

    746博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Spring源码解析之 IOC的主流程与注解加载bean的验证

java持续实践 发布时间:2021-03-10 07:48:39 ,浏览量:4

文章目录
      • 学习Spring源码的注意点
      • 基于注解加载Bean
      • 验证Controller等其他注解加载进容器

学习Spring源码的注意点
  1. 不要太在意版本的问题
  2. 不用太过于在意细节, 掌握主要流程为主
基于注解加载Bean

在之前的如下文章中, 是根据xml去加载Bean 的 https://javaweixin6.blog.csdn.net/article/details/113790554 本次改为根据注解把bean加载到容器中去 在Service的实现类中, 加上@Service 注解 Entrance类改造成为一个配置类. Entrance类如下

  1. 使用@Configuration注解标明是一个配置类
  2. 使用@ComponentScan 标明要扫描的包路径
  3. 使用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, 使用@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主流程如下

  1. 解析配置
  2. 定位与注册对象
  3. 注入对象
关注
打赏
1658054974
查看更多评论
立即登录/注册

微信扫码登录

0.3413s