码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC4 + Mybatis 零配置整理

时间:2017-07-25 19:57:38      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:springmvc4 零配置

------  WebInitializer.java      同xml配置的 web.xml


import javax.servlet.ServletContext;


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


import ch.qos.logback.ext.spring.web.LogbackConfigListener;



public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


@Override

protected Class<?>[] getRootConfigClasses() {

return new Class<?>[] { ApplicationContextConfig.class };

}


@Override

protected Class<?>[] getServletConfigClasses() {

return new Class<?>[] { WebMvcConfig.class };

}


@Override

protected String[] getServletMappings() {

return new String[] { "/" };

}


@Override

protected void registerContextLoaderListener(ServletContext servletContext) {

servletContext.setInitParameter("logbackConfigLocation", "classpath:logback.xml");

servletContext.addListener(LogbackConfigListener.class);

super.registerContextLoaderListener(servletContext);

}

}

------  WebMvcConfig.java    同xml配置的 spring-servlet.xml


import java.util.ArrayList;

import java.util.List;


import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.FilterType;

import org.springframework.http.MediaType;

import org.springframework.http.converter.HttpMessageConverter;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


import com.alibaba.fastjson.serializer.SerializerFeature;

import com.alibaba.fastjson.support.config.FastJsonConfig;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;


@Configuration

@EnableWebMvc

@ComponentScan(basePackages={"com.fang.demo"}, useDefaultFilters=false, includeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION, classes={Controller.class, ControllerAdvice.class})})

public class WebMvcConfig extends WebMvcConfigurerAdapter {


@Override

public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

configurer.enable();

}


@Override

public void configureViewResolvers(ViewResolverRegistry registry) {

registry.jsp("/", ".jsp");

}


@Override

public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { 

        // 使用fastJson工具

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        fastJsonConfig.setSerializerFeatures(

                SerializerFeature.PrettyFormat

        );

        // 解决乱码的问题

        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();

        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);

        fastConverter.setFastJsonConfig(fastJsonConfig);

        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        converters.add(fastConverter);

}

}



------- DataSourceConfig.java   数据源配置



import javax.sql.DataSource;


import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.annotation.EnableTransactionManagement;


import com.zaxxer.hikari.HikariConfig;

import com.zaxxer.hikari.HikariDataSource;


@Configuration

@EnableTransactionManagement

@PropertySource({"classpath:/config/jdbc.properties"})

public class DataSourceConfig {


@Value("${jdbc.hikari.driverClassName}")

private String driverClassName;

@Value("${jdbc.hikari.jdbcUrl}")

private String jdbcUrl;

@Value("${jdbc.hikari.username}")

private String username;

@Value("${jdbc.hikari.password}")

private String password;

@Value("${jdbc.hikari.readOnly}")

private boolean readOnly;

@Value("${jdbc.hikari.connectionTimeout}")

private long connectionTimeout;

@Value("${jdbc.hikari.idleTimeout}")

private long idleTimeout;

@Value("${jdbc.hikari.maxLifetime}")

private long maxLifetime;

@Value("${jdbc.hikari.maximumPoolSize}")

private int maximumPoolSize;

@Value("${jdbc.hikari.minimumIdle}")

private int minimumIdle;

@Value("${jdbc.hikari.dataSourceProperties.cachePrepStmts}")

private boolean cachePrepStmts;

@Value("${jdbc.hikari.dataSourceProperties.prepStmtCacheSize}")

private int prepStmtCacheSize;

@Value("${jdbc.hikari.dataSourceProperties.prepStmtCacheSqlLimit}")

private int prepStmtCacheSqlLimit;

@Value("${jdbc.hikari.dataSourceProperties.useServerPrepStmts}")

private boolean useServerPrepStmts;

@Bean(destroyMethod="close")

public DataSource dataSource() {

HikariConfig config = new HikariConfig();

config.setDriverClassName(driverClassName);

config.setJdbcUrl(jdbcUrl);

config.setUsername(username);

config.setPassword(password);

config.setReadOnly(readOnly);

config.setConnectionTimeout(connectionTimeout);

config.setIdleTimeout(idleTimeout);

config.setMaxLifetime(maxLifetime);

config.setMaximumPoolSize(maximumPoolSize);

config.setMinimumIdle(minimumIdle);

config.addDataSourceProperty("cachePrepStmts", cachePrepStmts);

config.addDataSourceProperty("prepStmtCacheSize", prepStmtCacheSize);

config.addDataSourceProperty("prepStmtCacheSqlLimit", prepStmtCacheSqlLimit);

config.addDataSourceProperty("useServerPrepStmts", useServerPrepStmts);

HikariDataSource ds = new HikariDataSource(config);

return ds;

}


@Bean

public PlatformTransactionManager transactionManager(DataSource dataSource) {

return new DataSourceTransactionManager(dataSource);

}

}


------- ApplicationContextConfig.java  同xml配置的 ApplicationContext.xml



import javax.sql.DataSource;


import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.EnableAspectJAutoProxy;

import org.springframework.context.annotation.FilterType;

import org.springframework.context.annotation.Import;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ControllerAdvice;


@Configuration

@ComponentScan(basePackages = { "com.fang.demo" }, excludeFilters = {

@ComponentScan.Filter(type = FilterType.ANNOTATION, value = { Controller.class, ControllerAdvice.class }) })

@EnableAspectJAutoProxy

@Import({ DataSourceConfig.class })

@MapperScan(basePackages="com.fang.demo", annotationClass=Mapper.class)

public class ApplicationContextConfig {


@Bean

public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {

SqlSessionFactoryBean factory = new SqlSessionFactoryBean();

factory.setDataSource(dataSource);

   PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

   factory.setMapperLocations(resolver.getResources("classpath:/mappers/*Mapper.xml"));

return factory.getObject();

}

}


SpringMVC4 + Mybatis 零配置整理

标签:springmvc4 零配置

原文地址:http://9318739.blog.51cto.com/9308739/1950844

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!