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应用程序的灵活性。

相关文章
相关标签/搜索