这里有dao、service和Servlet三个地方
通过配过文件xml生成对象,并注入对象类型的属性,降低耦合
dao文件代码:
package com.swift; public class DaoUser { public void fun() { System.out.println("I'm dao's fun()...................."); } }
service文件代码:(提供setter方法,xml文件可通过这种方法配置)
package com.swift; public class ServiceUser { private DaoUser daoUser; public void setDaoUser(DaoUser daoUser) { this.daoUser = daoUser; } public String fun() { System.out.println("I am Service's fun().............."); return daoUser.fun(); } }
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"> <!-- IoC 控制反转 Spring根据XML配置文件注入对象类型属性 --> <bean id="dao" class="com.swift.DaoUser"></bean> <bean id="service" class="com.swift.ServiceUser"> <property name="daoUser" ref="dao"></property> </bean> </beans>
Servlet类文件可以绕开dao的文件,直接使用service即可
package com.swift; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @WebServlet("/duixiang") public class ServletService extends HttpServlet { private static final long serialVersionUID = 1L; public ServletService() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); @SuppressWarnings("resource") ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); ServiceUser service=(ServiceUser) context.getBean("service"); response.getWriter().append(service.fun()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
中间因修改属性名字,而忽略修改setter方法名字导致出错,已改好,错误的类型记录了一下:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'daoUser' of bean class [com.swift.ServiceUser]: Bean property 'daoUser' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
提示的很好,要不自己很难发现。