Spring使用教程2--启动Spring容器

原创
2017/02/10 19:43
阅读数 649

启动Spring容器有以下四种方式:

1 使用spring中对Junit框架的整合功能启动Spring非Web容器(推荐)

此种方式一般用在单元测试中,需要引入junit4、spring的jar包、spring-test.jar

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-test</artifactId>  
    <version>3.1.1.RELEASE</version>  
</dependency> 
@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration({"classpath:applicationContext.xml"})  
public class ReadDaoImplTest {  
    @Resource ReadDao readDao;  
      
    @Test  
    public void getListTest(){  
        List<Client> clientList = readDao.getList("client.test", null);  
          
        for(Client c:clientList){  
            System.out.println(c.getVersionNum());  
        }  
    }  
}  

2 手动加载spring的配置文件的方式启动Spring非Web容器

此种方式一般用在单元测试中

public class ReadDaoImplTest {  
      
    public  static void main(String[] args){  
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  
        context.start();  
  
        ReadDao fqaService = (ReadDao) context.getBean("readDao");  
        System.out.println(fqaService);  
    }  
      
} 

3 使用web.xml配置启动Spring的web容器

3.1 方式一:使用xml加载配置文件的方式

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    <listener>
        <!-- 注册ContextLoaderListener -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <!-- 注册DispatcherServlet -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/spring/appServlet/servlet-context.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- DispatcherServlet映射 -->
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.2 方式二:从@Configuration注解的类中加载配置

     需要以下两步配置:

3.2.1 修改通用配置中的Web应用上下文实现

<context-param>  
    <param-name>contextClass</param-name>       
    <param-value>  
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext  
    </param-value>  
</context-param>  

3.2.2 指定加载配置类

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
        cn.javass.spring.chapter12.configuration.ApplicationContextConfig,  
        cn.javass.spring.chapter12.configuration.ApplicationContextConfig2  
    </param-value>  
</context-param>  
  • contextConfigLocation:除了可以指定配置类,还可以指定“扫描的类路径”,其加载步骤如下:

      1、首先验证指定的配置是否是类,如果是则通过注册配置类来完成Bean定义加载,即如通过ctx.register(ApplicationContextConfig.class)加载定义;

      2、如果指定的配置不是类,则通过扫描类路径方式加载注解Bean定义,即将通过ctx.scan("cn.javass.chapter12.confiuration")加载Bean定义。

3.2.3 完整示例配置 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- 使用Java配置 -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>

    <!-- 指定所使用的Java配置类 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>spittr.config.RootConfig</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 使用Java配置 -->
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <!-- 指定DispatcherServlet的配置类 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                spittr.config.WebConfigConfig
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

使用Java配置启动Spring的web容器(推荐)

4.1 使用前提

Servlet 3.0,例如Apache Tomcat 7或者更高

4.2 原理

在Servlet 3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果能发现的话,就会用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring 3.2引入了一个便利的WebApplicationInitializer基础实现,也就是AbstractAnnotationConfigDispatcherServletInitializer。因为只要我们自定义一个类扩展AbstractAnnotationConfigDispatcherServletInitializer(同时也就实现了WebApplicationInitializer),因此当部署到Servlet 3.0容器中的时候,容器会自动发现它,并用它来配置Servlet上下文。

4.3 方式一:继承WebApplicationInitializer接口

WebApplicationInitializer接口可以注册任意的servlet、filter、listener,当然也可以注册Spring的ContextLoaderListener和SpringMVC的DispatcherServlet,系统中可以有任意多个WebApplicationInitializer接口的实现类。

4.3.1 注册servlet

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import com.myapp.MyServlet;
public class MyServletInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 定义servlet
        Dynamic myServlet = servletContext.addServlet("myServlet", MyServlet.class);
        // 映射servlet
        myServlet.addMapping("/custom/**");
    }
}

4.3.2 注册filter

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // 注册一个filter
    javax.servlet.FilterRegistration.Dynamic filter = servletContext.addFilter("myFilter", MyFilter.class);
    // 添加映射
    filter.addMappingForUrlPatterns(null, false, "/custom/*");
}

4.4 方式二:继承AbstractAnnotationConfigDispatcherServletInitializer类(推荐)

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	/**
	 * 指定需要由DispatcherServlet映射的路径,这里给定的是”/”
	 */
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
    /**
     * 获取Spring应用容器的配置文件,这里我们给定预先定义的RootConfig.class
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }
    /**
     * 获取SpringMVC应用容器,这里传入预先定义好的WebConfig.class
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("spitter.web") // 激活Spring MVC
public class WebConfig extends WebMvcConfigurerAdapter {

    // 配置一个JSP视图解析器
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB_INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(basePackages = { "spitter" }, excludeFilters = {
        @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig {

}

 

展开阅读全文
打赏
1
5 收藏
分享
加载中
更多评论
打赏
0 评论
5 收藏
1
分享
返回顶部
顶部