Java-Web系列之Spring-Web

Spring Web

簡介

這個jar 文件包含Web 應用開發時,用到Spring 框架時所需的核心類,包括自動載入Web Application Context 特性的類、Struts 與JSF 集成類、文件上傳的支持類、Filter 類和大量工具輔助類。

容器初始化

啓動容器時需要自動裝載 ApplicationContext,而不是像之前用
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");

來初始化。Spring 提供的 ContextLoaderListener 就是爲了自動裝配 ApplicationContext 的配置信息

在pom.xml中添加依賴

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

配置 web.xml

web.xml 配置如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
  • 其中context-param指定了spring-context的配置文件,listener指定了項目啓動時的監聽

實現 ApplicationContextAware

當一個類實現了這個接口(ApplicationContextAware)之後,這個類就可以方便獲得 ApplicationContext 中的所有 bean。換句話說,就是這個類可以直接獲取 Spring 配置文件中,所有有引用到的 Bean 對象。

package com.domain.ssh.springWeb.commons;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContext implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext applicationContext;

    //銷燬時釋放applicationContext對象
    public void destroy() throws Exception {
        applicationContext = null;
    }

    //銷燬時釋放applicationContext對象
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext = applicationContext;
    }

    /**
     * 獲取Spring容器中的對象
     * @param beanId
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanId) {
        return (T) applicationContext.getBean(beanId);
    }

}

Spring-context 配置

注入 實現 ApplicationContextAware的類到Spring

<?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">

    <!--注入springContext到容器-->
    <bean id="springContext " class="com.domain.ssh.springWeb.commons.SpringContext"/>
    <!--把這個對象託管給Spring-->
    <bean id="userService" class="com.domain.ssh.spring.service.serviceImpl.UserServiceImpl" />
</beans>

創建接口和實現接口

創建UserService接口
package com.domain.hello.spring.service;

public interface UserService {
    public void sayHi();
}
創建UserServiceImpl 實現
package com.domain.hello.spring.service.impl;

import com.domain.hello.spring.service.UserService;

public class UserServiceImpl implements UserService {
    public void sayHi() {
        System.out.println("Hello Spring");
    }
}

測試

自動裝載ApplicationContext後來獲取Spring容器中的對象

定義路由,實現doGet方式
package com.domain.ssh.springWeb.controller;

import com.domain.ssh.spring.service.UserService;
import com.domain.ssh.springWeb.commons.SpringContext;

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 java.io.IOException;

@WebServlet(value = "/hello")
public class HelloController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       UserService userService = SpringContext.getBean("userService");
        userService.sayHi();
    }

}

基於註解的注入方式

之前在使用Spring的時候說過(見Spring章節),每一次注入一個對象,都需要在spring-context文件中配置。這種方式是通過xml的方式來注入對象,這裏學習通過註解的方式來注入

spring-context 配置文件

<?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:annotation-config />
    <context:component-scan base-package="com.domain.ssh.springWeb"/>
</beans>

使用註解方式後,配置文件中將不再需要定義一個一個的bean,只需要寫上打開註解模式<context:annotation-config />和指定掃描註解的包<context:component-scan base-package="com.domain.ssh.springWeb"/>這兩句話

註解方式注入Spring-Context

package com.domain.ssh.springWeb.commons;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext applicationContext;

    //銷燬時釋放applicationContext對象
    public void destroy() throws Exception {
        applicationContext = null;
    }

    //銷燬時釋放applicationContext對象
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext = applicationContext;
    }

    /**
     * 獲取Spring容器中的對象
     * @param beanId
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanId) {
        return (T) applicationContext.getBean(beanId);
    }

}

  • 通過@Component來注入Spring-Context

Spring提供了以下常用的注入註解

  • @Component
    用於注入普通java類
  • @Repository
    用於注入Dao層的實現類
  • @Service
    用於注入Service層的實現類
  • @Controller
    用於注入Controller的實現類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章