zoukankan      html  css  js  c++  java
  • Java框架spring 学习笔记(一):SpringBean、ApplicationContext 容器、BeanFactory容器

    Spring容器是Spring框架的核心,容器可以创建对象并创建的对象连接在一起,配置和管理他们的整个生命周期。Spring 容器使用依赖注入(DI)来作为管理应用程序的组件,被称为 Spring Beans。

    Spring提供两种不同类型的容器

    • ApplicationContext 容器
    • BeanFactory 容器

    ApplicationContext 容器包括 BeanFactory 容器的所有功能,如果资源足够建议使用ApplicationContext,在资源宝贵的移动设备或者基于 applet 的应用当中, BeanFactory 优先选择。

    新建配置文件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 容器

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

    目录结构如下:

    新建一个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的值。


    运行输出

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

  • 相关阅读:
    shell 测试命令
    shell 键盘录入和运算
    shell 的变量
    shell 脚本 helloworld
    让windows系统的DOS窗口也可以显示utf8字符集
    wxpython发布还自己图标的程序
    弥补wxpython无背景图片缺陷
    wxPython实现在浏览器中打开链接
    使用py2exe发布windows平台Python
    python os模块实用函数
  • 原文地址:https://www.cnblogs.com/zylq-blog/p/7792130.html
Copyright © 2011-2022 走看看