准備工作
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程序。
每天學習一點點,每天進步一點點。