Spring創建 BeanFactory 的方式
按照Bean的配置方式手動創建可以分為兩種:
-
使用
XMl配置的Bean
這種方式使用xml組態檔配置Bean的資訊并且設定掃描的路徑,掃描到的包可以使用注解進行配置Bean資訊,一般來說手動創建BeanFactory容器的實作類為ClassPathXmlApplicationContext和SystemFileXmlApplicationContext,設定xml的路徑即可創建出IOC容器,例如:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-test.xml"); User user = context.getBean(User.class); -
使用注解配置的
Bean這種方式不使用
xml組態檔,全部基于注解方式配置Bean的資訊,比如使用@Component、@Configuration進行Bean的配置,實作類為AnnotationConfigApplicationContext設定掃描的包,然后呼叫refresh方法進行IOC容器的創建,例如:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com.redwinter.test"); context.refresh();
但是一般來說開發中都是使用web容器進行IOC容器的創建的,比如tomcat容器、jetty容器、undertow容器、netty容器,在Spring中有一個BeanFactory的實作類:GenericApplicationContext,他的子類有一個叫GenericWebApplicationContext,在Spring Boot中,就是通過實作這個類完成Web容器的創建+IOC容器的創建的,在Spring Boot中有個類叫ServletWebServerApplicationContext就是繼承了GenericWebApplicationContext這個類,然后ServletWebServerApplicationContext中有個屬性叫webServer,這個是一個介面,這個介面對應的實作就是Web容器的實作:
public class ServletWebServerApplicationContext extends GenericWebApplicationContext
implements ConfigurableWebServerApplicationContext {
public static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet";
// web 容器,實作類有TomcatWebServer、JettyWebServer、NettyWebServer、UndertowWebServer
private volatile WebServer webServer;
// .... 去掉其他代碼
}
本文介紹使用XML組態檔手動創建IOC容器的方式
Spring 使用Xml啟動IOC容器
根據上一篇文章 https://www.cnblogs.com/redwinter/p/16151489.htmlSpring Bean IOC 的創建流程種的第一個方法AbstractApplicationContext#prepareRefresh前戲準備作業繼續解讀AbstractApplicationContext#refresh方法中的第二方法 AbstractApplicationContext#obtainFreshBeanFactory獲取BeanFactory,這個方法會創建一個DefaultListableBeanFactory 默認的可列出Bean的工廠,
AbstractApplicationContext#obtainFreshBeanFactory中主要是重繪BeanFactory,原始碼如下:
@Override
protected final void refreshBeanFactory() throws BeansException {
// 如果有BeanFactory 就銷毀掉并關閉
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
// 直接new一個BeanFactory 實作出來 DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 根據上一步創建BeanFactory創建的Id進行獲取
beanFactory.setSerializationId(getId());
// 定制化BanFactory ,比如設定allowBeanDefinitionOverriding 和allowCircularReferences 的屬性
customizeBeanFactory(beanFactory);
// 加載BeanDefinitions 從xml 和注解定義的Bean
// 從configLocations -> String[] -> String -> Resource[] -> Resource -> InputStream -> Document -> 決議成一個一個的BeanDefinition 物件
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
- 首先判斷是否已經有
BeanFactory了,如果有就銷毀掉并且關閉工廠 - 直接創建一個
BeanFactory,默認就是使用new DefaultListableBeanFactory,不過在創建的程序中可能會默認初始化一些屬性,比如:allowBeanDefinitionOverriding和allowCircularReferences允許Bean覆寫和解決回圈依賴的問題,還有就是BeanFactory的序列化id等屬性, - 設定序列化
id - 定制
BeanFactory,這里是一個擴展點,你可以對BeanFactory進行定制 - 加載
BeanDefinition,這里從XML組態檔中去加載,這里面的邏輯非常的復雜繁瑣 - 將創建的
BeanFactory設定出去
定制個性化的BeanFactory
在customizeBeanFactory(beanFactory);這個方法中,spring設定了兩個屬性,一個是設定是否可以覆寫Bean,一個是否允許回圈依賴,原始碼如下:
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
// 可以定制設定是否允許Bean覆寫
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// 可以定制設定是否允許回圈依賴
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}
spring提供了這個擴展點,那么我們就可以定制BeanFactory,比如我們新建一個類繼承ClassPathXmlApplicationContext,然后重寫customizeBeanFactory這個方法:
/**
* @author <a href="https://www.cnblogs.com/redwinter/">redwinter</a>
* @since 1.0
**/
public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext {
public MyClassPathXmlApplicationContext(String... configLocation) throws BeansException {
super(configLocation);
}
@Override
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
// 擴展點 設定不去處理回圈依賴或者beanDefinition覆寫
super.setAllowBeanDefinitionOverriding(true);
// 設定不允許回圈依賴
super.setAllowCircularReferences(false);
// 呼叫父類的方法
super.customizeBeanFactory(beanFactory);
}
}
創建兩個類,并且設定為回圈依賴:
/**
* @author <a href="https://www.cnblogs.com/redwinter/">redwinter</a>
* @since 1.0
**/
@Service
public class PersonService {
@Autowired
private UserService userService;
public void test() {
System.out.println(userService);
}
}
/**
* @author <a href="https://www.cnblogs.com/redwinter/">redwinter</a>
* @since 1.0
**/
@Service
public class UserService {
@Autowired
private PersonService personService;
public void test(){
System.out.println(personService);
}
}
創建之后然后使用自定義的MyClassPathXmlApplicationContext類進行啟動:
/**
* @author <a href="https://www.cnblogs.com/redwinter/">redwinter</a>
* @since 1.0
**/
public class BeanCreate {
@Test
public void classPathXml() {
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-test.xml");
ClassPathXmlApplicationContext context = new MyClassPathXmlApplicationContext("classpath:spring-test.xml");
UserService userService = context.getBean(UserService.class);
userService.test();
}
}
啟動之后發現報錯了:
四月 19, 2022 1:26:55 下午 org.springframework.context.support.AbstractApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personService': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'personService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'personService': Requested bean is currently in creation: Is there an unresolvable circular reference?
如果設定為true,那么啟動不會報錯了并且輸出了:
com.redwinter.test.service.PersonService@6fc6f14e
BeanDefinition 的加載
在重繪BeanFactory的方法中,有個方法叫loadBeanDefinitions,這個方法就是進行BeanDefinition的加載的,他的大致流程是這樣的:

在BeanDefinition加載的程序中,有個關鍵點可以讓我們自定義標簽進行BeanDefinition的加載和決議,在設定決議器的時候,Spring是這樣設定決議器的:
public DelegatingEntityResolver(@Nullable ClassLoader classLoader) {
// 創建dtd決議器
this.dtdResolver = new BeansDtdResolver();
// 創建schema 決議器
// 在Debug的時候,這里會呼叫toString方法,然后去呼叫getSchemaMappings 方法,將schemaMappings 設定屬性進去
this.schemaResolver = new PluggableSchemaResolver(classLoader);
}
在Spring中一般決議XML檔案的時候都是從網上下載對應的標簽決議,比如Spring組態檔中的https://www.springframework.org/schema/beans/spring-beans-3.1.xsd ,但是一般來說都是不需要進行下載的,Spring提供了本地檔案的xsd檔案,這些xsd檔案就配置在META-INF/spring.schemas檔案中進行配置,由于檔案中內容比較多我就不復制出來了,
在Spring進行xml決議之前會創建一個namespace的處理器的決議器:
public NamespaceHandlerResolver getNamespaceHandlerResolver() {
if (this.namespaceHandlerResolver == null) {
// 創建默認的namespace處理器決議器,加載spring.handlers中配置的處理器
this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver();
}
return this.namespaceHandlerResolver;
}
這里創建的namespace處理器就是放在META-INF/spring.handlers檔案中,比如util標簽、context標簽的都是在這個檔案中配置的處理器,對于util標簽的namespace處理器如下:
public class UtilNamespaceHandler extends NamespaceHandlerSupport {
private static final String SCOPE_ATTRIBUTE = "scope";
@Override
public void init() {
// 注冊constant標簽的決議器
registerBeanDefinitionParser("constant", new ConstantBeanDefinitionParser());
// 注冊property-path標簽的決議器
registerBeanDefinitionParser("property-path", new PropertyPathBeanDefinitionParser());
// 注冊list標簽的決議器
registerBeanDefinitionParser("list", new ListBeanDefinitionParser());
// 注冊set標簽的決議器
registerBeanDefinitionParser("set", new SetBeanDefinitionParser());
// 注冊map標簽的決議器
registerBeanDefinitionParser("map", new MapBeanDefinitionParser());
// 注冊properties標簽的決議器
registerBeanDefinitionParser("properties", new PropertiesBeanDefinitionParser());
}
// ....省略其他代碼
}
這些處理器加載完之后就會進行BeanDefinition的決議:
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
// 如果節點是默認的命名空間則使用默認的決議
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
// 定制的namespace標簽
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
// 決議import節點
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
// 決議alias 別名節點
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
// 決議bean節點
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
// 決議beans節點
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
決議完之后就會呼叫注冊,將決議到的BeanDefinition放在beanDefinitionMap和beanDefinitionNames集合中,最終完成了BeanDefinition的加載程序,
現在開發基本都是使用Spring Boot,是全注解方式,這種BeanDefinition的加載實際上就是指定了一個包的掃描,然后掃描這些包下標記了@Configuration、@Component、@Service、@Controller等注解的類,感興趣的可以去看下AnnotationConfigApplicationContext這個類是如何掃描的,
這就是Spring BeanFactory的創建程序,并且包括了BeanDefinition的加載程序,接下來我們進行自定義標簽,讓spring進行決議,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458606.html
標籤:Java
