由于最近學Spring Boot的時候接觸了IntelliJ IDEA,覺得它在架構內建和支援方面做得的确比老邁的Eclipse好太多了;而且IDEA原生支援Spring,這就省去了很多不必要的環節,是以就用它了。好了,Talk is cheap,show me the code.
一、建立工程:

File->new->project,選擇“Spring“,選擇勾選Spring(預設就是選中的),然後Next,再輸入工程名,點選Finish,在短暫的下載下傳後,就可以開始愉快地敲代碼了。
二、先寫一個沒用到架構時的Hello World
2.1、一個普通的實體類
package com.myspring.test;
public class Hello {
private String name;
public void showName() {
System.out.println("name is: "+name);
}
public void setName(String name) {
this.name = name;
}
}
2.2、一個普通的測試類
package com.myspring.test;
public class Test {
public static void main(String[] args){
Hello hello=new Hello();//建立一個Hello類對象hello
hello.setName("Microsoft");//為hello的屬性指派
hello.showName();//調用方法
}
}
2.3、運作結果如下:
至此,一個跟Spring完全沒有關系的Hello World就寫完了。
三、想要将這個改造成使用Spring的版本需要做哪些工作:
3.1、在spring-config.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="hello" class="com.myspring.test.Hello">
<property name="name" value="Microsoft"></property>
</bean>
</beans>
這裡需要手動完成的隻有<bean></bean>标簽内的内容,根标簽下的内容在建立工程的時候就已經完成了。
3.2、在main()方法中需要對建立Hello類對象的步驟進行修改
package com.myspring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args){
// Hello hello=new Hello();
// hello.setName("Microsoft");
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-config.xml");
Hello hello= (Hello) ctx.getBean("hello");
hello.showName();
}
}
3.3、然後就可以看一下最終成果了:
好了,最後來梳理一下整個過程吧:
1、建立一個新工程,選擇spring工程,并勾選“Create empty spring-config.xml”;
2、寫一個實體類,并在測試類中實作對該類某個屬性的列印;
3、在spring-config.xml檔案配置該對象的屬性,包括bean的id(對象的名稱,genBean()方法根據該參數擷取對象)、class(類名的完整包名),property的name(類的屬性名)和value(該類屬性的值);
3、在測試類中将建立類對象步驟,改用spring架構中的ClassPathXmlApplicationContext()讀取xml檔案的方法來實作,将對象交由spring容器來管理,并為該對象指派。
4、方法調用步驟不變。