spring的入门程序
1.在Eclipse中创建Java项目,并将spring的四个核心包和依赖包添加到src里,发布到类路劲下,项目如图所示:
2.UserDao程序如下:
package com.itheima.ioc; public interface UserDao { public void say(); }
3.UserDaoImpl如下:
package com.itheima.ioc; public class UserDaoImpl implements UserDao { @Override public void say() { System.out.println("UserDao say hello Word!"); } }
4.applicationContext.xm如下
配置文件的名称可以随便写,通常在实际开发中都写成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-4.3.xsd"> <!-- 将指定的类配置给Spring,让Spring创建其对象的实例 --> <bean id="userDao" class="com.itheima.ioc.UserDaoImpl"/> </beans>
5.测试程序如下:
package com.itheima.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class IocTest { public static void main(String[] args) { //1.初始化spring容器,加载配置文件 ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml"); //2.通过容器来获取userDao实例 UserDao userDao=(UserDao) applicationContext.getBean("userDao"); //3.调用实例的方法 userDao.say(); } }
测试结果如下: