Java框架spring 學習筆記(一):SpringBean、ApplicationContext 容器、BeanFactory容器

Spring容器是Spring框架的核心,容器能夠建立對象並建立的對象鏈接在一塊兒,配置和管理他們的整個生命週期。Spring 容器使用依賴注入(DI)來做爲管理應用程序的組件,被稱爲 Spring Beans。java

 

Spring提供兩種不一樣類型的容器spring

  • ApplicationContext 容器
  • BeanFactory 容器

ApplicationContext 容器包括 BeanFactory 容器的全部功能,若是資源足夠建議使用ApplicationContext,在資源寶貴的移動設備或者基於 applet 的應用當中, BeanFactory 優先選擇。app

 

新建配置文件Beans.xml框架

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <beans xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 7 
 8    <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
 9        <property name="message" value="Hello World!"/>
10    </bean>
11 
12 </beans>

 

 

ApplicationContext 容器spa

新建一個spring的工程,使用spring框架code

目錄結構以下:xml

 

新建一個HelloWorld.java文件對象

 1 package com.example.spring;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Application {
 7     public static void main(String[] args) {
 8         //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml
 9         //使用Application容器
10         ApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");
11         HelloWorld obj = (HelloWorld)context.getBean("helloWorld");
12         obj.getMessage();
13     }
14 }

HelloWorld obj = (HelloWorld)context.getBean("helloWorld"),經過查找配置文件中的id爲helloWorld中的內容,爲obj對象配置message的值。blog


運行輸出
生命週期

Your Message : Hello World!

 

BeanFactory 容器

修改Application.java

 1 package com.example.spring;
 2 
 3 import org.springframework.beans.factory.BeanFactory;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Application {
 7     public static void main(String[] args) {
 8         //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml
 9         //使用BeanFactory容器
10         BeanFactory factory = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");
11         HelloWorld obj = (HelloWorld)factory.getBean("helloWorld");
12         obj.getMessage();
13     }
14 }

運行輸出

Your Message : Hello World!

 

經過更改Beans.xml 中的值「message」 屬性的值能夠修改HelloWorld類中的值,而且保持兩個源文件不變,能夠看到Spring應用程序的靈活性。

相關文章
相關標籤/搜索