我是靠谱客的博主 敏感小丸子,最近开发中收集的这篇文章主要介绍servlet3.0+SpringMVC出去所有xml配置:实现零配置,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在Spring/springMVC项目中总会有一些xml配置如:web.xml ;application.xml 、dispatcher-servlet.xml 但是进入servlet3.0 后 这些配置都可以使用注解来完成;

本次环境使用Spring4xx + servlet3.0 、Tomcat8

除去web.xml文件

<?xml version="1.0" encoding="UTF-8"?>  
<web-app 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_3_0.xsd"
 version="3.0">

 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:dispatcher-servlet.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

</web-app>  

 实现代码

package com.wisely;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class ContainerWebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        servletContext.setInitParameter("contextConfigLocation","classpath:applicationContext.xml");

        ServletRegistration.Dynamic registration  = servletContext.addServlet("dispatcher",new DispatcherServlet());
        registration .addMapping("/");
        registration .setLoadOnStartup(1);
        registration .setInitParameter("contextConfigLocation","classpath:dispatcher-servlet.xml");
        
        servletContext.addListener(new ContextLoaderListener());

    }
}

这里需要继承WebApplicationInitializer 接口 具体请看:http://datum.iteye.com/blog/1537632

除去 dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 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
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc.xsd">

 <mvc:annotation-driven />

 <context:component-scan base-package="com.xxg.controller" />

 <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/jsp/" />
 <property name="suffix" value=".jsp" />
 </bean>

</beans> 

代码

package com.wisely.config;

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

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.*.controller")
public class DispatcherServletConfig {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    } 
}

除去application.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"
 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
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd">

 <context:component-scan base-package="com.xx">
 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
 </context:component-scan>

 <context:property-placeholder location="classpath:db-config.properties"/>

 <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
 <property name="driverClassName" value="${jdbc.driverClassName}"/>
 <property name="url" value="${jdbc.url}"/>
 <property name="username" value="${jdbc.username}"/>
 <property name="password" value="${jdbc.password}"/>
 </bean>

</beans>  

其中数据库的相关配置从db-config.properties配置文件读取:

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://localhost:3306/mydb  
jdbc.username=root  
jdbc.password=123456  

代码

package com.wisely.config;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.sql.DataSource;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.wisely",excludeFilters = {@ComponentScan.Filter(value = Controller.class)})
public class ApplicationConfig {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 必须加上static
     */
    @Bean
    public static PropertyPlaceholderConfigurer loadProperties() {
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        ClassPathResource resource = new ClassPathResource("config.properties");
        configurer.setLocations(resource);
        return configurer;
    }
}

或者使用注解 

@PropertySource("classpath:db-config.properties")

就不无需Bean

/**
 * 必须加上static
 */
@Bean
public static PropertyPlaceholderConfigurer loadProperties() {
    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    ClassPathResource resource = new ClassPathResource("config.properties");
    configurer.setLocations(resource);
    return configurer;
}

修改ContainerWebInitializer

package com.wisely;

import com.wisely.config.ApplicationConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class ContainerWebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ApplicationConfig.class);
        servletContext.addListener(new ContextLoaderListener(rootContext));
        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(DispatcherServlet.class);
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher",new DispatcherServlet(webContext));
        registration.addMapping("/");
        registration.setLoadOnStartup(1);
    }
}

 

转载于:https://my.oschina.net/u/1414315/blog/979336

最后

以上就是敏感小丸子为你收集整理的servlet3.0+SpringMVC出去所有xml配置:实现零配置的全部内容,希望文章能够帮你解决servlet3.0+SpringMVC出去所有xml配置:实现零配置所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部