servlet調用spring容器中的bean,的兩種方式一種註解一種xml配置

來源:互聯網
上載者:User

最近由於項目中出現了Servlet調用Spring的bean,由於整個項目中所有的bean均是註解方式完成,如@Service,@Repository,@Resource等,但是Spring的容器管理是不識別Servlet和filter的,所以無法使用註解方式引用,在網上查了資料後看到如下的代碼:
第一種方式:在Servlet的init方法中來完成bean的執行個體化,初始化後可以在servlet中調用bean中的方法

  1. WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); 
  2. ts=(TestService)cont.getBean("testService")//ts為已經聲明的類變數,括弧內的名字預設為bean的類名,第一個字母小寫,也可以設定唯一名稱,如@Service(value="testService")

複製代碼

第二種方式:直接在Servlet的doPost方法中擷取,代碼如下

  1. WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());

複製代碼

不過在我的項目中使用上面任何一種都無法得到任何bean,原因是上面的兩種方式只對xml配置的bean有效,無法擷取到註解的bean,最後在網上看到一篇關於“Spring對註解(Annotation)處理源碼分析——掃描和讀取Bean定義”的文章,才終於解決了這個問題,代碼如下:
代碼1:Service介面

  1. package com.test.web.service;

  2. public interface ITestService {
  3. public void test();//測試方法
  4. }

複製代碼

代碼2:實現介面並使用註解方式

  1. package com.test.web.service.impl;

  2. import org.springframework.stereotype.Service;

  3. import com.taokejh.web.test.ITestService;
  4. //此處的註解部分可以給出唯一名稱,如@Service(value="testServiceImpl"),等同於xml配置中bean的id
  5. @Service
  6. public class TestServiceImpl implements ITestService {

  7. @Override
  8. public void test() {
  9. System.out.println("測試列印");
  10. }

  11. }

複製代碼

代碼3:在Servlet中擷取註解的bean並調用其測試方法

  1. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
  2. ctx.scan("com.test.web.service.*"); 
  3. ctx.refresh(); 
  4. TestServiceImpl service = ctx.getBean(TestServiceImpl.class);//此處也可以使用ctx.getBean("testServiceImpl") 
  5. service.test();

複製代碼

這樣就可以在Servlet或者filter中調用Spring註解方式的bean,其實整個過程就是類比了SpringMVC在初始化的時候掃描組件包後完成對所有bean的註冊並存放至管理容器中。如果大家有更好的解決辦法,希望不吝賜教!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.