输出Hello World!
1.我们首先要创建一个动态Web项目,配置Tomcat,并且导入jar包建立path
目录结构:
2.创建Dao包,在Dao包下创建接口TestDao
package dao;
public interface TestDao {
public void sayHello();
}
3.在Dao下,创建TestDao接口的实现类TestDaoImpl
package dao;
public class TestDaoImpl implements TestDao {
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Hello World!");
}
}
4.创建配置文件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创建其实例 -->
<bean id="test" class="dao.TestDaoImpl" />
</beans>
5.创建测试类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!