Spring HelloWorld

下载spring: 

http://repo.spring.io/release/org/springframework/spring/5.1.7.RELEASE/spring-framework-5.1.7.RELEASE-dist.zip

下载commons-logging:http://mirrors.tuna.tsinghua.edu.cn/apache//commons/logging/binaries/commons-logging-1.2-bin.tar.gz 

 

建立一个Java Project:

Spring HelloWorld

 项目右击:

Spring HelloWorld

添加下面的包,注意第一个包。Spring HelloWorld

beans.xml的写法

Spring HelloWorld

 下载的压缩包中有说明

Spring HelloWorld

beans.xml放在src中

 HelloWorld.java:

public class HelloWorld {
    private String msg;
    public void setMsg(String msg) {
        this.msg=msg;
    }
    public void getMsg() {
        System.out.println("msg:" + msg);
    }
}


Main.java:

Main.java:

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

public class Main {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloworld");
         obj.getMsg();
    }
}

 


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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloworld" class="HelloWorld"> 
      <property name="msg" value="Hello World!"/>
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

运行

Spring HelloWorld

结束。