輸出Hello World!
1.我們首先要創(chuàng)建一個動態(tài)Web項目,配置Tomcat,并且導(dǎo)入jar包建立path
目錄結(jié)構(gòu):

image
2.創(chuàng)建Dao包,在Dao包下創(chuàng)建接口TestDao
package dao;
public interface TestDao {
public void sayHello();
}
3.在Dao下,創(chuàng)建TestDao接口的實現(xiàn)類TestDaoImpl
package dao;
public class TestDaoImpl implements TestDao {
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Hello World!");
}
}
4.創(chuàng)建配置文件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">
<!-- 將指定類TestDaoImpl配置給Spring,讓Spring創(chuàng)建其實例 -->
<bean id="test" class="dao.TestDaoImpl" />
</beans>
5.創(chuàng)建測試類test.java
package test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.TestDao;
public class Test {
public static void main(String[] args) {
// 初始化Spring容器ApplicationContext,加載配置文件
ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
TestDao tt = (TestDao) appCon.getBean("test");// test為配置文件中的id
tt.sayHello();
}
}
6.最后運行項目(Run As Java Application),在命令臺中輸出Hello World!

image