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.