文章目录
Spring入门
总结
BeanFactory 和 ApplicationContext 的区别
BeanFactory 才是 Spring 容器中的顶层接口。
ApplicationContext 是它的子接口。
BeanFactory 和 ApplicationContext 的区别:
创建对象的时间点不一样。
ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
BeanFactory:什么使用什么时候创建对象。
第一步:拷贝必备的 jar 包到工程的 lib 目录中
第二步:在类的根路径下创建一个任意名称的 xml 文件(不能是中文)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
第三步:调用
public static void main(String[] args) {
//资源文件的定位
Resource resource = new ClassPathResource("spring-config.xml");
//容器初始化
BeanFactory factory = new XmlBeanFactory(resource);
//或者
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//从容器中获取对象
HelloBean bean = (HelloBean) factory.getBean("helloBean");
HelloBean bean4 = (HelloBean) factory.getBean("helloBean");
HelloBean bean2 = (HelloBean) context.getBean("helloBean");
HelloBean bean3 = (HelloBean) context.getBean("helloBean");
//操作bean对象
System.out.println(bean.getHello());
System.out.println(bean2.getHello());
System.out.println(bean2.hashCode());
System.out.println(bean3.hashCode());
}