Spring架構 註解annotation和設定檔混合使用(產生對象與屬性注入) xml設定檔沒有提示解決,springannotation
使用設定檔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