使用配置文件xml生成对象
使用注解注入属性
分别制作两个dao的类StudentDao.class 和CourseDao.class
然后制作一个service的类Service.class
最后通过一个Servlet类ServletTest.class进行测试
StudentDao.class类的代码如下:
package com.swift; public class StudentDao { public String fun() { return "This is StudentDao's fun()........"; } }
CourseDao.class类的代码如下:
package com.swift; public class CourseDao { public String fun() { return "This is CourseDao's fun()......."; } }
Service.class类的代码如下:
package com.swift; import javax.annotation.Resource; public class Service { @Resource(name="studentDao") private StudentDao studentDao; @Resource(name="courseDao") private CourseDao courseDao; public String fun() { return "This is Service's fun()........."+this.studentDao.fun()+this.courseDao.fun(); } }
在类的属性上边直接通过annotation注解的方法注入对象属性 ,这个对象是在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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.swift"></context:component-scan> <bean id="studentDao" class="com.swift.StudentDao"></bean> <bean id="courseDao" class="com.swift.CourseDao"></bean> <bean id="service" class="com.swift.Service"></bean> </beans>
ServletTest.class类的代码如下:
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("/test") public class ServletTest extends HttpServlet { private static final long serialVersionUID = 1L; public ServletTest() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); ApplicationContext context=new ClassPathXmlApplicationContext("beanZhujie.xml"); Service service=(Service) context.getBean("service"); response.getWriter().append(service.fun()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
浏览器结果如下图:
xml配置文件没有提示解决
window -->preferences-->搜索 xml catalog -->add-->在key中输入约束网址http://www.springframework.org/schema/beans/spring-beans.xsd
-->在location中点击按钮 file system-->找到spring framework 包-->schema-->beans-->最后的那个版本高的-->key type下拉菜单选schema location