環境已經安裝完成,接下來建立一個簡單的Spring應用。java
建立Spring應用步驟:spring
打開Eclipse,若是尚未搭建開發環境,可參照Spring開發環境搭建(Eclipse) ,選擇菜單:File > New > Maven Project
,彈出對話框,以下圖操做apache
點擊Next
,彈出對話框,以下圖操做編程
點擊Finish
,完成項目建立,項目結構以下:app
項目目錄說明:框架
項目根目錄下的pom.xml文件就是maven的依賴包配置文件。maven
要把用到的spring模塊添加到項目中來。修改pom.xml
,引入以下模塊:測試
完整的pom.xml
文件內容:this
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.qikegu.demo</groupId> <artifactId>spring-helloworld</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> </dependencies> </project>
接下來將添加代碼,會添加以下文件:spa
最終的項目結構以下圖所示:
後面將詳細說明。
添加Customer
Bean類。項目根目錄右鍵彈出菜單,選擇:New -> File
, 指定目錄.../src/main/java/com/qikegu/demo
,添加Customer.java文件。
Customer.java
代碼:
package com.qikegu.demo; public class Customer { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void displayInfo() { System.out.println("Hello: "+ name); } }
這是一個簡單的bean類,包含一個屬性及其getter和setter方法,另外displayInfo()
方法會打印客戶名稱。
在resources目錄下,添加Bean的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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="customerBean" class="com.qikegu.demo.Customer"> <property name="name" value="奇客谷"></property> </bean> </beans>
<bean>
標記爲指定的類定義bean。<property>
標記是bean的一個子元素,用於設置Customer
類的屬性,設置的屬性值將由IoC容器賦值給Customer
類實例。添加主類文件Hello.java
,內容以下:
package com.qikegu.demo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Hello { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Customer customerBean = (Customer) context.getBean("customerBean"); customerBean.displayInfo(); ((ClassPathXmlApplicationContext) context).close(); } }
右鍵單擊Hello.java
,彈出菜單,選擇Run As > Java Application
,輸出:
Hello: 奇客谷