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 @ 2022-04-05 10:10  emanlee  阅读(75)  评论(0编辑  收藏  举报