1 開發工具與必要jar包
1.1 下載STS工具
資源鏈接-> STS 3.9.2,可以修改鏈接中版本號,以下載不同版本的STS,如 STS 3.9.0 與 STS 3.9.2 鏈接地址基本相同,僅版本號不同。
1.2 導入必要包
資源l鏈接->spring-framework-4.0.0.RELEASE-dist,可以修改鏈接中版本號,以下載不同版本的spring-framework,如spring-framework-4.1.0.RELEASE-dist 與 spring-framework-4.0.0.RELEASE-dist 鏈接地址基本相同,僅版本號不同。
在spring框架中,必須導入的包主要有:
通過右鍵項目名,【Build Path】->【Add External Archives】,選中上述 jar 包添加到項目中。
(或【Build Path】->【Configure Build Path】->【Libraries】->【Add External JARs】,選中上述 jar 包添加到項目中)
1.3 導入源碼
爲方便查看底層源碼,需要導入源碼,源碼仍然在 spring-framework 文件中(帶 sources 的jar包)。
通過右鍵項目名,【Build Path】->【Configure Build Path】->【Libraries】,選中需要導入源碼的 jar 包,並展開下拉列表,可以看到 Source attachment:(None),雙擊此文件進入 Source Attachment Configuration 導航界面,選擇【External location】,選擇需要導入源碼文件。
從圖中可以看到,導入源代碼後的 Source attachment 文件後接的是文件地址,而未導入的接的是None。
2 快捷鍵
爲方便編程,先介紹幾個很實用的快捷鍵,詳見->STS快捷鍵
- Alt + /:智能填充
- Ctrl + Shift + O:生成 import
- Alt + Shift + S:生成setters方法、getters方法、toString方法、構造方法等
- Ctrl + Shift + F:代碼格式化
- Ctrl + Alt + ↓ :複製當前行到下一行(複製增加)
- Ctrl + Alt + ↑ :複製當前行到上一行(複製增加)
- Alt + ↓ :當前行和下面一行交互位置
- Alt + ↑ :當前行和上面一行交互位置
3 案例
項目結構如下:
(1)src文件
Person.java
package com.test;
public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
Test.java
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Person p=ac.getBean("person",Person.class);
System.out.println(p);
}
}
(2)配置文件
applicationContext.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="person" class="com.test.Person">
<property name="id" value="101"></property>
<property name="name" value="小明"></property>
</bean>
</beans>
(3)運行結果
Person [id=101, name=小明]