吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2876|回复: 5
收起左侧

[Java 转载] SSM javaConfig配置整合

[复制链接]
chg122345 发表于 2018-7-23 12:49


Spring上下文的配置

[Asm] 纯文本查看 复制代码
@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;
    }

}


数据源配置
[Asm] 纯文本查看 复制代码
@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的配置
[Java] 纯文本查看 复制代码
// 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
实用帖子
萌萌哒的小白 发表于 2018-7-23 13:05
我想请教下,能否用spring mvc +spring +hibernate 呢?为啥常见的是用mybaties,用hibernate会出现什么问题吗?
13551494196 发表于 2018-7-23 13:16
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。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-15 18:01

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表