在IDEA中使用Spring寫一個HelloWorld


准備工作


1、使用IDEA2018專業版,

我試了IDEA2019教育版和IDEA2020社區版,都無法順利創建一個Spring項目,實在是惱火,一氣之下,統統卸載掉。

重裝了一個IDEA2018專業版,突然就變得很順利了。

2、在IDEA中安裝Spring插件

點擊File--settings--Plugins,搜索“Spring”,安裝Spring Assistant。

新建Spring項目


1、新建項目:New--Project,選擇Spring

項目名為“hellospring”

IDEA有一個好處,當你創建spring項目時,它會自動下載所需要的spring包。

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

3、在hello包下創建兩個class源文件:HelloWorld.java MainApp.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,點擊確定。

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>

其實我們需要添加的只有這三行:

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

class 屬性表示需要注冊的 bean 的全路徑,這里就是HelloWorld.java的文件路徑

id 則表示 bean 的唯一標記。

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

此時的目錄結構如下:

忽略掉out目錄,那是程序運行之后自動生成的。

運行MainApp.java文件

輸出結果如下:

試一下,修改value中的值,比如,改成下面這樣:

<bean id="helloWorld" class="hello.HelloWorld">
        <property name="message" value="你好,Spring!"/>
    </bean>

再運行MainApp.java,結果如下:

就這樣,成功創建了第一個Spring程序。

每天學習一點點,每天進步一點點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM