spring框架bean加载 一

Spring 框架源码解析:类加载过程原理

spring框架使用很广泛,既然使用很多,那么我们就应该对其了解,便于在工作中能更好的使用,遇到问题我们可以更快的排查,或者难道大家知道它是如何工作的吗?后续的几篇文章会介绍spring 加载xml并加载bean的过程,会有部分代码以及流程图,如有不对的地方大家还应该指出。

我们先上一段我们的测试代码:

public class TestService {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("application.xml");
        // 使用类型获取
        SpringService service = app.getBean(SpringService.class);
        // 使用类名获取
        // SpringService service1 = (SpringService) app.getBean("springServiceImpl");
        service.springServicePrint();
    }
}

SpringService就是一个简单的接口:

public interface SpringService {

    public String springServicePrint();
}

SpringService的实现类:SpringServiceImpl代码如下:

public String springServicePrint() {
        String printStr = "测试";
        System.out.println(printStr + " impl");
        return printStr;
}

resources中增加application.xml配置文件(本实例中我们使用component-scan来扫描加载类),内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"
    default-autowire="byName">
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <context:component-scan base-package="com" />
</beans>

下面我们就开始看看整体流程:

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {
        super(parent);
        // 配置xml文件路径
        setConfigLocations(configLocations);
        if (refresh) {
        // 真正的加载逻辑方法(关键)
            refresh();
        }
    }
  1. spring如何加载xml文件setConfigLocations
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值