Spring入门初体验
Spring其实就是一个容器,让我们更方便的拿到想要的对象。
1.编写一个service
// userService.java public interface userService { public void insertUser(); } // xmlImpl.java public class xmlImpl implements userService{ @Override public void insertUser() { System.out.println("insert a user"); } }
2.编写Spring核心配置文件,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"> <bean id="userService" class="service.xmlImpl"></bean> </beans>
3.使用
例如写一个servlet文件,在doGet那调用
public class userView extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取Spring容器context ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 方式1,靠id拿bean userService service = (userService) context.getBean("userService"); service.insertUser(); // 方式2,靠class拿bean userService service2 = context.getBean(userService.class); service2.insertUser(); response.getWriter().println("123"); } }