1.使用Eclipse创建Web应用并导入JAR包 2. 创建接口TestDao 3.创建接口TestDao的实现类TestDaoImpl 4.创建配置文件applicationContext.xml 5.创建测试类
package dao; public interface TestDao { public void sayHello(); }
package dao; public class TestDaoImpl implements TestDao{ @Override public void sayHello() { System.out.println("Hello, Study hard!"); } }
<?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>
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import dao.TestDao; public class Test { public static void main(String[] args) { @SuppressWarnings("resource") ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml"); // 通过容器获取test实例 TestDao tt = (TestDao) appCon.getBean("test");// test为配置文件中的id tt.sayHello(); } }