文章目錄
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());
}