不借助Maven,使用Eclipse创建Hello World级别的Spring项目

时间:2022-07-22
本文章向大家介绍不借助Maven,使用Eclipse创建Hello World级别的Spring项目,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文适合没有任何Spring基础的初学者。

从下面的链接下载Spring库文件:

https://repo.spring.io/release/org/springframework/spring/5.0.0.RELEASE/

http://commons.apache.org/proper/commons-logging/download_logging.cgi

以及apache Common logging:

在Eclipse里创建一个Java项目:

在Config Build Path里,点击Add External Jars,将之前下载的Spring库文件解压出的lib文件夹里的jar文件加入项目依赖:

  • commons-logging-1.1.1
  • spring-aop-4.1.6.RELEASE
  • spring-aspects-4.1.6.RELEASE
  • spring-beans-4.1.6.RELEASE
  • spring-context-4.1.6.RELEASE
  • spring-context-support-4.1.6.RELEASE
  • spring-core-4.1.6.RELEASE
  • spring-expression-4.1.6.RELEASE
  • spring-instrument-4.1.6.RELEASE
  • spring-instrument-tomcat-4.1.6.RELEASE
  • spring-jdbc-4.1.6.RELEASE
  • spring-jms-4.1.6.RELEASE
  • spring-messaging-4.1.6.RELEASE
  • spring-orm-4.1.6.RELEASE
  • spring-oxm-4.1.6.RELEASE
  • spring-test-4.1.6.RELEASE
  • spring-tx-4.1.6.RELEASE
  • spring-web-4.1.6.RELEASE
  • spring-webmvc-4.1.6.RELEASE
  • spring-webmvc-portlet-4.1.6.RELEASE
  • spring-websocket-4.1.6.RELEASE

新建HelloWorld.java:

package com.sap;

public class HelloWorld {
	   private String message;
	   public void setMessage(String message){
	      this.message  = message;
	   }
	   public void getMessage(){
	      System.out.println("Your Message : " + message);
	   }
	}

以及MainApp.java:

package com.sap;

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();
   }
}

这里的ClassPathXmlApplicationContext() API用于创建应用程序的上下文。这个 API 加载 beans 的配置文件并最终基于所提供的 API,它处理创建并初始化所有的对象,即在配置文件中提到的 beans。

使用已创建的上下文的getBean() 方法来获得所需的 bean。这个方法使用 bean 的 ID 返回一个最终可以转换为实际Java对象HelloWorld的通用对象。

创建一个 Bean 的配置文件,该文件是一个 XML 文件,并且作为粘合 bean 的粘合剂即类:

<?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="com.sap.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

当 Spring 应用程序被加载到内存中时,框架利用了上面的配置文件来创建所有已经定义的 beans,并且按照标签的定义为它们分配一个唯一的 ID。

执行MainApp.java, 控制台里看到Hello World!

说明这个最简单的Spring应用运行成功了: