剛剛從eclipse轉到IDEA,對於idea上面的許多都不太熟,特此筆記
打開idea——新建項目——選擇Spring——如果用不到spring其他可以不勾選——勾選創建xml文件——下一步後輸入項目名稱(項目名稱不建議使用中文)——完成
編輯完成後的項目結構如下:
代碼如下:
IHello.java
package com.spring.chapter1;
/**
* 接口類
*/
public interface IHello {
public void sayHello();
}
HelloImpl.java
package com.spring.chapter1;
/**
* 實現類
*/
public class HelloImpl implements IHello {
@Override
public void sayHello() {
System.out.println("--- HelloWorld!!! ---");
}
}
HelloTest.java
package com.spring.chapter1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 測試類
*/
public class HelloTest {
public static void main(String[] args) {
new HelloTest().test();
}
public void test(){
//1、讀取配置文件實例化一個IoC容器
// 默認sources根目錄爲src目錄
// ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//將項目根目錄作爲sources根目錄
// ApplicationContext context = new ClassPathXmlApplicationContext("spring-config2.xml");
//將resources目錄作爲sources根目錄
// ApplicationContext context = new ClassPathXmlApplicationContext("spring-config3.xml");
//將resources目錄作爲sources根目錄
ApplicationContext context = new ClassPathXmlApplicationContext("chapter1/spring-config4.xml");
//2、從容器中獲取Bean,注意此處完全“面向接口編程,而不是面向實現”
IHello hello = context.getBean("hello", IHello.class);
//3、執行業務邏輯
hello.sayHello();
}
}
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">
<!-- id 表示你這個組件的名字,class表示組件類 -->
<bean id="hello" class="com.spring.chapter1.HelloImpl"></bean>
</beans>
注意:
1、idea的默認sources根目錄爲src目錄,使用 spring-config.xml 配置文件時不需要更改sources目錄
2、使用spring-config2.xml 時需要將sources目錄設置爲項目所在目錄
3、使用spring-config 3/4 .xml 時需要將sources目錄設置爲resources目錄
設置方法:打開項目結構--Modules--點擊項目名稱--sources下的resources--點擊相應目錄即可設置爲sources根目錄