spring核心容器创建的两种方式

1.spring核心容器

BeanFactory
ApplicationContext
其中BeanFactory使用绝对路径加载配置文件
ApplicationContext使用相对路径加载配置文件

2.例子

在这里插入图片描述

package main.java;

public class Hello {

	public void say(){
		System.out.println("hello spring");
	}
	
}

resource:

<?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="hello" class="main.java.Hello">
	</bean>
</beans>

2.1 BeanFactory绝对路径:

package main.test;

import main.java.Hello;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class Main {

	public static void main(String[] args) {

		BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource(
				"G:\\Study_spring\\helloSpring\\src\\main\\resource\\applicationContext.xml"));
		Hello hello = beanFactory.getBean(Hello.class);
		hello.say();
		
	}

}

在这里插入图片描述

2.2ApplicationContext相对路径

package main.test;

import main.java.Hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"main/resource/*.xml");
		Hello hello = (Hello) applicationContext.getBean("hello");
		hello.say();
	}

}

3.分析

每种方式都有自己的好处与坏处,但是因为绝对路径用到的情况较少,大多还是使用相对路径。

4.扩展:ApplicationContext是一个接口:

按住ctrl左键点击ApplicationContext
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
就可以查看源码。

ApplicationContext是一个接口,spring框架实现的两个子类:
FileSystemXmlApplicationContext
ClassPathXmlApplicationContext
当然并不是直接实现接口,他们之间有好几重的关系,继承关系。
同样的,FileSystemXmlApplicationContext是使用绝对路径的配置文件,
ClassPathXmlApplicationContext是使用相对路径的配置文件。。

5.分析

BeanFactory在加载bean时,如果属性初始化不会自检,如果属性没有注入,加载bean后,调用getBean方法会报错。
ApplicationContext在加载bean时,会在初始化进行自检,有利于检查依赖的属性是否注入。

实际中大多使用ApplicationContext.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值