Spring實(shí)戰(zhàn) - 使用getBean方式裝配Bean

1、在pom.xml中增加spring-web依賴

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.2.RELEASE</version>
</dependency>

2缭贡、在web.xml中引入spring-context

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

3栅隐、實(shí)現(xiàn)ApplicationContextAware和DisposableBean接口,獲取ApplicationContext中所有的bean屈糊。

package com.codeonline.cats.commons.context;

import com.sun.media.jfxmediaimpl.MediaDisposer.Disposable;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


/**
 * @author 碼出高薪
 * @Desc. 獲取bean 實(shí)例
 * @date 2020/1/13 08:52
 */

public class SpringContext implements ApplicationContextAware, Disposable {

  private static final Logger logger = LoggerFactory.getLogger(SpringContext.class);

  private static ApplicationContext applicationContext;

  /**
   * 根據(jù)beanId 獲取實(shí)例
   * @param beanId
   * @param <T>
   * @return 
   */
  public static <T> T getBean(String beanId){
    assertContextInjected();
    return (T) applicationContext.getBean(beanId);
  }

  /**
   * 根據(jù)clazz 獲取實(shí)例
   * @param clazz
   * @param <T>
   * @return
   */
  public static <T> T getBean(Class<T> clazz){
    assertContextInjected();
    return applicationContext.getBean(clazz);
  }
  /**
   * 清空ApplicationContext.
   */
  public void dispose() {
    logger.debug("清空ApplicationContext");
    applicationContext = null;
  }
  /**
   * 實(shí)現(xiàn)ApplicationContextAware接口, 注入Context到靜態(tài)變量中.
   */
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContext.applicationContext = applicationContext;
  }
  /**
   * 檢查ApplicationContext不為空.
   */
  private static void assertContextInjected(){
    Validate.validState(applicationContext != null, "在spring-context中沒有定義SpringContext對(duì)象.");
  }
}

4的榛、在service 目錄下創(chuàng)建MyUserService接口

package com.codeonline.cats.service;

/**
 * @author 碼出高薪
 * @Desc. 創(chuàng)建MyUserService接口
 * @date 2020/1/13 11:04
 */
public interface MyUserService {
  String sayHello();
}

5、在service 目錄中創(chuàng)建impl
選擇service->右鍵->New->Package->impl
6逻锐、在impl 目錄中創(chuàng)建MyUserService接口實(shí)現(xiàn)類MyUserServiceImpl

package com.codeonline.cats.service.impl;

import com.codeonline.cats.service.MyUserService;

/**
 * @author 碼出高薪
 * @Desc. 創(chuàng)建MyUserService接口實(shí)現(xiàn)類
 * @date 2020/1/13 11:10
 */

public class MyUserServiceImpl implements MyUserService {

  public String sayHello() {
    return "Hello, Spring Web ";
  }
}

7夫晌、在spring-context 增加bean,myUserService 和springContext

<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <!--  Service -->
  <bean id="myUserService" class="com.codeonline.cats.service.impl.MyUserServiceImpl"/>
  <!--  Spring Context  -->
  <bean id="springContext" class="com.codeonline.cats.commons.context.SpringContext"/>
</beans>

8昧诱、在Controller 創(chuàng)建MyUserServiceController

package com.codeonline.cats.web.controller;

import com.codeonline.cats.commons.context.SpringContext;
import com.codeonline.cats.service.MyUserService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 碼出高薪
 * @Desc. 調(diào)用MyUserService中的sayHello()
 * @date 2020/1/13 11:18
 */

public class MyUserServiceController extends HttpServlet {

/**
 * 獲取Spring容器初始化bean慷丽, MyUserService
  */
private MyUserService myUserService = SpringContext.getBean("myUserService");
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String hello = myUserService.sayHello();
    req.setAttribute("hello",hello);
    req.getRequestDispatcher("index.jsp").forward(req,resp);
  }
}

10、 在webapp目錄下創(chuàng)建index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>整合Spring web</title>
</head>
<body>
${hello}
</body>
</html>

11鳄哭、在web.xml中增加servlet

  <servlet>
    <servlet-name>MyUserServiceController</servlet-name>
    <servlet-class>com.codeonline.cats.web.controller.MyUserServiceController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyUserServiceController</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

12、運(yùn)行項(xiàng)目纲熏,在瀏覽器中輸入http://localhost:8080/hello

整合Spring web.png

至此妆丘,完成Spring web 整合

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過簡(jiǎn)信或評(píng)論聯(lián)系作者局劲。
  • 序言:七十年代末勺拣,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鱼填,更是在濱河造成了極大的恐慌药有,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,627評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件苹丸,死亡現(xiàn)場(chǎng)離奇詭異愤惰,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)赘理,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門宦言,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人商模,你說我怎么就攤上這事奠旺。” “怎么了施流?”我有些...
    開封第一講書人閱讀 169,346評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵响疚,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我瞪醋,道長(zhǎng)忿晕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,097評(píng)論 1 300
  • 正文 為了忘掉前任银受,我火速辦了婚禮杏糙,結(jié)果婚禮上慎王,老公的妹妹穿的比我還像新娘。我一直安慰自己宏侍,他們只是感情好赖淤,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,100評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著谅河,像睡著了一般咱旱。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上绷耍,一...
    開封第一講書人閱讀 52,696評(píng)論 1 312
  • 那天吐限,我揣著相機(jī)與錄音,去河邊找鬼褂始。 笑死诸典,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的崎苗。 我是一名探鬼主播狐粱,決...
    沈念sama閱讀 41,165評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼胆数!你這毒婦竟也來了肌蜻?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,108評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤必尼,失蹤者是張志新(化名)和其女友劉穎蒋搜,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體判莉,經(jīng)...
    沈念sama閱讀 46,646評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡豆挽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,709評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了券盅。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片祷杈。...
    茶點(diǎn)故事閱讀 40,861評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖渗饮,靈堂內(nèi)的尸體忽然破棺而出但汞,到底是詐尸還是另有隱情,我是刑警寧澤互站,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布私蕾,位于F島的核電站,受9級(jí)特大地震影響胡桃,放射性物質(zhì)發(fā)生泄漏踩叭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,196評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望容贝。 院中可真熱鬧自脯,春花似錦、人聲如沸斤富。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽满力。三九已至焕参,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間油额,已是汗流浹背叠纷。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留潦嘶,地道東北人涩嚣。 一個(gè)月前我還...
    沈念sama閱讀 49,287評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像掂僵,于是被迫代替她去往敵國(guó)和親航厚。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,860評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容