chg122345 发表于 2018-7-23 12:49

SSM javaConfig配置整合



Spring上下文的配置

@Configuration
@ComponentScan(basePackages = "org.jleopard.mall.service")
@Import({DataSourceConfig.class})
public class RootConfig {

    @Bean
    public BeanNameAutoProxyCreator proxyCreator(){
      BeanNameAutoProxyCreator proxyCreator = new BeanNameAutoProxyCreator();
      proxyCreator.setProxyTargetClass(true);
      proxyCreator.setBeanNames("*Service");
      proxyCreator.setInterceptorNames("transactionInterceptor");
      return proxyCreator;
    }

}

数据源配置

@Configuration
@MapperScan(basePackages = "org.jleopard.mall.dao")
public class DataSourceConfig {

    private String url = "jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";

    private String username = "root";

    private String password = "root";

    private String driverClass = "com.mysql.jdbc.Driver";

    private int initialSize = 5;

    private int minIdle = 5;

    private int maxActive = 20;

    private int maxWait = 60000;

    private int timeBetweenEvictionRunsMillis = 60000;

    private int minEvictableIdleTimeMillis= 30000;

    private String validationQuery = "SELECT 1 FROM DUAL";

    private boolean testWhileIdle = true;

    private boolean testOnBorrow = false;

    private boolean testOnReturn = false;

    private boolean poolPreparedStatements = true;

    private int maxPoolPreparedStatementPerConnectionSize = 20;

    private String filters = "stat,wall,slf4j";

    private String connectionProperties = "druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000";

    @Bean
    public DataSource dataSource(){
      DruidDataSource dataSource = new DruidDataSource();
      dataSource.setUrl(url);
      dataSource.setUsername(username);
      dataSource.setPassword(password);
      dataSource.setDriverClassName(driverClass);

      dataSource.setInitialSize(initialSize);
      dataSource.setMinIdle(minIdle);
      dataSource.setMaxActive(maxActive);
      dataSource.setMaxWait(maxWait);
      dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
      dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
      dataSource.setValidationQuery(validationQuery);
      dataSource.setTestWhileIdle(testWhileIdle);
      dataSource.setTestOnBorrow(testOnBorrow);
      dataSource.setTestOnReturn(testOnReturn);
      dataSource.setPoolPreparedStatements(poolPreparedStatements);
      dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
      try {
            dataSource.setFilters(filters);
      } catch (SQLException e) {
            throw new RuntimeException("druid configuration initialization filter----->>:", e);
      }
      dataSource.setConnectionProperties(connectionProperties);
      return dataSource;
    }

    private org.apache.ibatis.session.Configuration getConfiguration(){
      org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
      configuration.setCacheEnabled(true);
      configuration.setDefaultStatementTimeout(3000);
      configuration.setMapUnderscoreToCamelCase(true);
      configuration.setUseGeneratedKeys(true);
      configuration.setUseColumnLabel(true);
      return configuration;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
      SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
      try {
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactoryBean.setConfiguration(getConfiguration());
            sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath:mapper/*.xml"));
            sqlSessionFactoryBean.setTypeAliasesPackage("org.jleopard.mall.dao");
      } catch (IOException e) {
            throw new RuntimeException("初始化sessionFactoryBean失败.." , e);
      }
      return sqlSessionFactoryBean;
    }
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(){
      DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
      dataSourceTransactionManager.setDataSource(dataSource());
      return dataSourceTransactionManager;
    }

    @Bean(name="transactionInterceptor")
    public TransactionInterceptor interceptor(){
      TransactionInterceptor interceptor = new TransactionInterceptor();
      interceptor.setTransactionManager(dataSourceTransactionManager());

      Properties transactionAttributes = new Properties();
      transactionAttributes.setProperty("*","PROPAGATION_REQUIRED");

      interceptor.setTransactionAttributes(transactionAttributes);
      return interceptor;
    }
}

MVC的配置

// MVC 配置
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.jleopard.mall.controller" )
public class AppConfig implements WebMvcConfigurer {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
      configurer.enable();
    }

    /*
   * STEP 1 - Create SpringResourceTemplateResolver
   * */
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
      SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
      templateResolver.setCharacterEncoding("UTF-8");
      templateResolver.setApplicationContext(applicationContext);
      templateResolver.setPrefix("/WEB-INF/templates/");
      templateResolver.setSuffix(".html");
      templateResolver.setTemplateMode(TemplateMode.HTML);
      templateResolver.setCacheable(false);
      return templateResolver;
    }

    /*
   * STEP 2 - Create SpringTemplateEngine
   * */
    @Bean
    public SpringTemplateEngine templateEngine() {
      SpringTemplateEngine templateEngine = new SpringTemplateEngine();
      templateEngine.setTemplateResolver(templateResolver());
      templateEngine.setEnableSpringELCompiler(true);
      return templateEngine;
    }

    /*
   * STEP 3 - Register ThymeleafViewResolver
   * */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
      ThymeleafViewResolver resolver = new ThymeleafViewResolver();
      resolver.setCharacterEncoding("UTF-8");
      resolver.setTemplateEngine(templateEngine());
      registry.viewResolver(resolver);
    }

    @Bean
    public ResourceHttpRequestHandler uploadHandler() {

      ResourceHttpRequestHandler font = new ResourceHttpRequestHandler();

      List<Resource> locations = new ArrayList<>();

      ServletContextResource scr = new ServletContextResource(servletContext,"/uploads/");

      locations.add(scr);

      font.setLocations(locations);

      return font;

    }

    @Bean
    public ResourceHttpRequestHandler staticHandler() {

      ResourceHttpRequestHandler staticHandler = new ResourceHttpRequestHandler();

      List<Resource> locations = new ArrayList<>();
      ServletContextResource scr = new ServletContextResource(servletContext,"/static/");
      locations.add(scr);

      staticHandler.setLocations(locations);

      return staticHandler;

    }

    @Bean
    public SimpleUrlHandlerMapping handlerMapping() {

      SimpleUrlHandlerMapping shm = new SimpleUrlHandlerMapping();

      Properties properties = new Properties();
       properties.setProperty("/static/**","staticHandler");
      properties.setProperty("/uploads/**", "uploadHandler");

      shm.setMappings(properties);

      return shm;

    }

    @Bean
    public CommonsMultipartResolver multipartResolver() {
      CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
      multipartResolver.setMaxUploadSize(30*1024*1024);
      multipartResolver.setMaxInMemorySize(10*1024*1024);
      return multipartResolver;
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {

      SimpleMappingExceptionResolver smer = new SimpleMappingExceptionResolver();

      return smer;

    }

    @Bean
    public RestTemplate restTemplate(){

      RestTemplate rt=new RestTemplate();

      rt.getMessageConverters().add(new org.springframework.http.converter.FormHttpMessageConverter());

      return rt;
    }

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping(){

      RequestMappingHandlerMapping rmhm = new RequestMappingHandlerMapping();

      //interceptor
       /* Object[] interceptors = {new TokenInterceptor()};
      rmhm.setInterceptors(interceptors);*/ //TODO
      return rmhm;
    }
}


// 初始化 相当于web.xml
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected Class<?>[] getRootConfigClasses() {
      return new Class[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
      return new Class[]{AppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
      return new String[]{"/"};
    }
}

chg122345 发表于 2018-7-23 12:51

{:1_893:} 实用帖子

萌萌哒的小白 发表于 2018-7-23 13:05

我想请教下,能否用spring mvc +spring +hibernate 呢?为啥常见的是用mybaties,用hibernate会出现什么问题吗?

13551494196 发表于 2018-7-23 13:16

感谢分享{:1_927:}

wuye996 发表于 2018-7-23 13:54

萌萌哒的小白 发表于 2018-7-23 13:05
我想请教下,能否用spring mvc +spring +hibernate 呢?为啥常见的是用mybaties,用hibernate会出现什么问题吗 ...

一些老的项目是用的Hibernate不过现在新项目都是Mybatis了

chg122345 发表于 2018-7-24 20:53

萌萌哒的小白 发表于 2018-7-23 13:05
我想请教下,能否用spring mvc +spring +hibernate 呢?为啥常见的是用mybaties,用hibernate会出现什么问题吗 ...

mybatis更灵活,自己写sql 。运维的人也都能看懂。hibernate深入要花些时间,学起来自然更难一些,hibernate虽然有良好的sql封装,但特定的需求还是得自己写hql。
页: [1]
查看完整版本: SSM javaConfig配置整合