首先下載所需的jar包
新建一個工程,創建一個HelloService接口
public interface HelloService { public void hello(); }
新建一個類HelloServiceImpl實現接口
public class HelloServiceImpl implements HelloService{
public void hello(){
System.out.println("Hello World!");
}
}
新建一個helloworld.xml文件(在src目錄下)
<?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="helloService" class="HelloServicImpl" />
</beans>
現在要實例化一個IOC容器,然後從容器中獲取所需的對象,調用接口完成我們的功能。寫一個測試類
public class HelloTest {
@Test
public void testHelloWorld() {
// 1、讀取配置文件實例化一個IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
// 2、從容器中獲取Bean,注意此處完全“面向接口編程,而不是面向實現”
HelloService helloService = context.getBean("helloService", HelloService.class);
// 3、執行業務邏輯
helloService.hello();
}
getBean裏的參數helloService是id,HelloService.class是接口
右鍵運行JUnit Test,Console成功輸出helloworld。