2. Spring 的 HelloWorld

初学Spring,就先来写一个 Spring 的 HelloWorld 吧

1. 首先,新建一个 java Project(因为暂时不需要网页,所以就不用创建 web 项目了)

2. 导入 Spring 基本的几个 jar 包导入到项目中,分别是:

  

其中,commons-logging-1.2.jar 是 commons 工具包下的一个 jar 包,spring 中的 jar 包依赖这个包,所以要一起加上。加上之后要记得进行 Build Path --> Add to Build Path 这个操作

3. 现在开始写一个 HelloWorld 类,下面是代码:

package com.spring.helloworld;

public class HelloWorld {
    
    private String userName;
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public void helloWorld(){
        System.out.println(userName + " : helloWorld!");
    }
}
HelloWorld类代码

4. 写完代码后,在类路径下添加一个 Spring Bean Configuration File 文件

这是一个 XML 文件,在这个文件里,我们可以配置 Bean,以及其他的一些东西

在这个文件中,我们配置刚才写的那个 HelloWorld 类,代码如下:

<?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.xsd">

    <bean id="helloWorld" class="com.spring.helloworld.HelloWorld">
        <property name="userName" value="Chao"></property>
    </bean>
</beans>
Spring Bean Configuration File 代码

5. 现在,我们再写一个测试类,用来调用在配置文件里面配置的 HelloWorld 类:

package com.spring.test;

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

import com.spring.helloworld.HelloWorld;

public class TestMain {
    public static void main(String[] args) {
        
        // 创建 Spring 的 IOC 容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("BeanConfiguration.xml");
        // 从 IOC 中获取 HelloWorld 对象
        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
        // 执行HelloWorld 的 helloWorld() 方法
        helloWorld.helloWorld();
    }
}
TestMain

执行这个方法,成功!

原文地址:https://www.cnblogs.com/zyx1301691180/p/7662378.html