Spring 一个简单的Spring程序

一个简单的Spring程序

1. 创建Java类

创建 net.biancheng 包,在该包下创建 HelloWorld.java 和 MainApp.java 类。

HelloWorld.java 类的代码如下。

复制代码
package net.biancheng;

public class HelloWorld {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("message : " + message);
    }
}
复制代码

 

 

MainApp.java 类的代码如下。

复制代码
package net.biancheng;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();
    }
}
复制代码

 

关于以上代码,需要注意以下两点:

  1. 创建 ApplicationContext 对象时,我们使用了 ClassPathXmlApplicationContext 类。该类用于加载 Spring 配置文件、创建和初始化所有对象,也就是下面配置文件中提到的 Bean。
  2. ApplicationContext.getBean() 方法用来获取 Bean,该方法返回值类型为 Object,通过强制类型转换为 HelloWorld 的实例对象,根据该对象调用类中的方法。

2. 创建配置文件

在 src 目录下创建 Spring 配置文件 Beans.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="helloWorld" class="net.biancheng.HelloWorld">
        <property name="message" value="Hello World!" />
    </bean>

</beans>
复制代码

 

您也可以将该配置文件命名为其它有效的名称。需要注意的是,该文件名必须与 MainApp.java 中读取的配置文件名称一致。

Beans.xml 用于给不同的 Bean 分配唯一的 ID,并给相应的 Bean 属性赋值。例如,在以上代码中,我们可以在不影响其它类的情况下,给 message 变量赋值。

 

来源:

http://c.biancheng.net/spring/module.html

http://c.biancheng.net/spring/first-spring.html

posted @   emanlee  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
· 分享4款.NET开源、免费、实用的商城系统
历史上的今天:
2021-04-05 安装 Altium Designer(AD20)
2021-04-05 列线图(Alignment Diagram),又称诺莫图(Nomogram图)
2009-04-05 格式化SQL代码语句 format t-sql
2009-04-05 javascript格式化日期
2009-04-05 Javascript对日期的操作,日期函数
2009-04-05 如何成为编写程序的高手
2009-04-05 先为成功的人工作,再与成功的人合作,最后是让成功的人为你工作
点击右上角即可分享
微信分享提示