准备工作
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="myTestBean" class="com.spring.config.entity.MyTestBean" ><property name="id" value="123456"/></bean></beans>
MyTestBean
package com.spring.config.entity;/*** @author 1* @version 1.0* @description: TODO* @date 2024-03-13 16:50*/
public class MyTestBean {private String id;public String getId() {return id;}public void setId(String id) {this.id = id;}@Overridepublic String toString() {return "MyTestBean{" +"id='" + id + '\'' +'}';}public MyTestBean(String id) {this.id = id;}public MyTestBean() {}}
入口main方法
package com.spring.config.controller;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 源码入口** @author 1* @version 1.0* @description: TODO* @date 2024-05-08 10:41*/
public class Day1Demo {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");Object myTestBean = applicationContext.getBean("myTestBean");System.out.println(myTestBean);}
}
进入源码
debug模式,F7
static {//急切地加载ContextClosedEvent类以避免奇怪的类加载器问题WebLogic 8.1中的应用程序关闭。(达斯汀·伍兹报道)//me:可能是作者也解决不了的问题,如果不加载这个类,程序无法启动// Eagerly load the ContextClosedEvent class to avoid weird classloader issues// on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.)ContextClosedEvent.class.getName();}
/*** Create a new ClassPathXmlApplicationContext with the given parent,* loading the definitions from the given XML files.* @param configLocations array of resource locations* @param refresh whether to automatically refresh the context,* loading all bean definitions and creating all singletons.* Alternatively, call refresh manually after further configuring the context.* @param parent the parent context* @throws BeansException if context creation failed* @see #refresh()*/public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)throws BeansException {//调用父类的构造方法,进行相关对象的创建super(parent);//设置配置,替换占位符setConfigLocations(configLocations);if (refresh) {refresh();}}
可以看到核心方法refresh()