目录
1.使用Eclipse创建Web应用Spring-test1
5.在src目录下,创建Spring的配置文件applicationContext.xml。
7.在applicationContext.xml文件中使用实现类TestDaoImpl创建一个id为test的Bean,代码如下:
9.执行该java application,控制台输出Hello,Spring,程序成功。
1.使用Eclipse创建Web应用Spring-test1
2.在Web项目中导入JAR包
3.创建接口TestDao
4.创建接口TestDao的实现类TestDaoImpl
5.在src目录下,创建Spring的配置文件applicationContext.xml。
6.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">
<!-- 配置service
<bean> 配置需要创建的对象
id :用于之后从spring容器获得实例时使用的
class :需要创建实例的全限定类名
-->
</beans>
7.在applicationContext.xml文件中使用实现类TestDaoImpl创建一个id为test的Bean,代码如下:
<?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">
<!-- 配置service
<bean> 配置需要创建的对象
id :用于之后从spring容器获得实例时使用的
class :需要创建实例的全限定类名
-->
<bean id="test" class="dao.TestDaoImpl" />
<bean id="userServiceId" class="service.UserServiceImpl"></bean>
</beans>
8.编写主方法进行测试。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.TestDao;
public class TestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
String xmlPath = "applicationContext.xml";
@SuppressWarnings("resource")
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//2获得内容 --不需要自己new,都是从spring容器获得
TestDao test = (TestDao) applicationContext.getBean("test");
test.sayHello();
}
}