1. 程式人生 > 實用技巧 >用Spring寫一個HelloWorld

用Spring寫一個HelloWorld

1、在IDEA中安裝Spring外掛

點選File--settings--Plugins,搜尋“Spring”,安裝Spring Assistant。

新建Spring專案

1、新建專案:New--Project,選擇Spring

IDEA有一個好處,當你建立spring專案時,它會自動下載所需要的spring包

2、右鍵src,建立一個包(Package),名字叫作"hello"吧。

3、在hello包下建立兩個class原始檔:HelloWorld.javaMainApp.java

其中,HelloWorld.java中寫入:

package hello;

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

 上面MainApp.java檔案裡,有一個Beans.xml

這是一個配置檔案,需要手動建立它。

4、建立配置檔案Beans.xml

右鍵src--New--XML Configuation File--Spring Config

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

    <bean id="helloWorld" class="hello.HelloWorld">
        <property name="message" value="Hello World!"/>
    </bean>

</beans>

class 屬性表示需要註冊的 bean 的全路徑,這裡就是HelloWorld.java的檔案路徑

id 則表示 bean 的唯一標記。

這裡的value中的值,就是輸出到螢幕上的內容。

總結: