找了好久都没找到 Java整合SSM 网上大多数都是 xml方式,Servlet 3.0 时代 Spring官方好早就建议使用配置类配置 Spring了,今天刚好分享一下我自己研究的配置类怎么写。
SpringConfig.java
package com.xian.config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@ComponentScan("com.xian.service")
@MapperScan(basePackages = "com.xian.mapper")
@PropertySource("classpath:hikari.properties")
public class SpringConfig {
@Autowired
private Environment env;
@Bean
@Scope
public DataSource dataSource(){
HikariConfig config = new HikariConfig();
config.setDriverClassName(env.getProperty("hikari.driver-class-name"));
config.setJdbcUrl(env.getProperty("hikari.jdbc-url"));
config.setUsername(env.getProperty("hikari.username"));
config.setPassword(env.getProperty("hikari.password"));
config.setMaxLifetime(Long.parseLong(env.getProperty("hikari.max-lifetime")));
config.setPoolName(env.getProperty("hikari.pool-name"));
config.setAutoCommit(Boolean.parseBoolean(env.getProperty("hikari.auto-commit")));
config.setMaximumPoolSize(Integer.parseInt(env.getProperty("hikari.maximum-pool-size")));
config.setIdleTimeout(Integer.parseInt(env.getProperty("hikari.idle-timeout")));
config.setMinimumIdle(Integer.parseInt(env.getProperty("hikari.minimum-idle")));
config.setConnectionTestQuery(env.getProperty("hikari.connection-test-query"));
config.setConnectionTimeout(Integer.parseInt(env.getProperty("hikari.connection-timeout")));
return new HikariDataSource(config);
}
@Bean
@Scope
public SqlSessionFactory sessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
return sqlSessionFactoryBean.getObject();
}
@Bean
@Scope
public DataSourceTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
SpringMvcConfiguration.java
package com.xian.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
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.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.util.ArrayList;
import java.util.List;
@Configuration
@ComponentScan("com.xian.controller")
@EnableWebMvc
public class SpringMvcConfiguration implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean(name = "internalResourceViewResolver")
public ViewResolver viewResolver(){
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/static/");
internalResourceViewResolver.setSuffix(".html");
return internalResourceViewResolver;
}
@Bean(name = "RequestMappingHandlerAdapter")
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(){
RequestMappingHandlerAdapter requestMappingHandlerAdapter = new RequestMappingHandlerAdapter();
List<HttpMessageConverter<?>> messageConverterList = new ArrayList<>();
messageConverterList.add(new MappingJackson2HttpMessageConverter());
requestMappingHandlerAdapter.setMessageConverters(messageConverterList);
return requestMappingHandlerAdapter;
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new DateFormatter());
WebMvcConfigurer.super.addFormatters(registry);
}
}
WebAppInitializer.java
package com.xian.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfiguration.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
return new Filter[]{encodingFilter};
}
}
时间类型转换器
DateFormatter.java
package com.xian.config;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
@Component
public class DateFormatter implements Formatter<Date> {
public DateFormatter() {
super();
}
@Override
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
@Override
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {
final String format = "yyyy-MM-dd";
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
}
}
这里是我的项目源文件
SSM-by-confgClass: 通过配置类的方式整合SSM,内含一个自定义转换器