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

  • 相关阅读:
    第一章ASP.NET SignalR简介
    第六章SignalR的服务器广播
    第五章SignalR的实时高频通讯
    第四章SignalR自托管主机
    第三章SignalR在线聊天例子
    第二章SignalR所支持的平台
    DevExpress ASPxHtmlEditor控件格式化并导出Word (修复中文字体导出丢失)
    改进的简单Tooltips显示
    C# WebForm 使用NPOI 2 生成简单的word文档(.docx)
    一些自用的小工具,分享给非程序猿们
  • 原文地址:https://www.cnblogs.com/zylq-blog/p/7792130.html
Copyright © 2020-2023  润新知