javascript
不借助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/beanshttp://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應用運行成功了:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的不借助Maven,使用Eclipse创建Hello World级别的Spring项目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 视效大片!《变形金刚7:超能勇士崛起》确
- 下一篇: Spring里的容器和Bean对象