美文网首页
SpringBoot无XML配置

SpringBoot无XML配置

作者: ChoviWu | 来源:发表于2018-01-03 01:09 被阅读64次

    简书上排版可能不是很好,如果想了解可以点我的博客园链接

    SpringBoot,自己研究了好几天,以前也是没有接触过这类的框架,不过原理吧,也就是那么些个原理,毕竟都是Spring开源下的子框架。好了,回归正题,今天晚上研究了好久,写出来了无配置文件的javaConfig配置,Demo集成了SpringMvc + mybatis + boot  ,里面也含有hibernate的core包,用来生成数据库表结构的。首先 ,添加如下boot官方提供的依赖包:

    spring-boot-starter-web 4 5 6    org.mybatis.spring.boot

    mybatis-spring-boot-starter 1.1.1

    spring-boot-starter-data-jpa 1.5.7.RELEASE

    上面的就是配置中所需要的架包,因为本demo体现的是无配置文件,所以demo里不会有什么配置文件(yaml除外)我使用的数据源是阿里的Druid  另外还有分页的架包以及mybatis整合spring的架包

    com.github.pagehelper       pagehelper 2.1

    org.mybatis   mybatis   3.4.0

            org.mybatis       mybatis-spring       1.2.3

    jar包现在已经分配完毕(注意jar包的版本号,个人发现很多问题都出在了jar包冲突或者版本不一致的身上了)

    本demo 演示的编辑工具是 IDEA 因为我创建的是springboot项目

    下来创建配置文件(jdbc.properties以及 javaConfig )jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true jdbc.user=root jdbc.password= #jdbc.driver=com.mysql.jdbc.Driver jdbc.initialSize=5

    jdbc.minIdle=1

    jdbc.maxActive=10

    jdbc.filters=stat

    这和普通大多数项目的一样,可以粘过来!现在,我来开始配置 数据源 以及 业务层配置

    import javax.sql.DataSource;

    import java.sql.SQLException;

    import java.util.ArrayList;

    import java.util.List;

    import java.util.Properties;

    /** * 配置业务层 */

    @Configuration//配置的注解

    @EnableTransactionManagement//事务管理的注解 @PropertySource("classpath:jdbc.properties")//属性扫描注解

    public class SqlSessionFactoryConfig implements TransactionManagementConfigurer{   

    //创建全局数据源

    protected DataSource dataSource;

    //mybatis配置

    private static String Mybatis_Config = "mybatis-config.xml";     //类的别名     private static String ALIASMODEL = "com.example.model";   

    //mapper 包的位置

    private static String MAPPERPATH = "com.example.mapper";   //mapper.xml 编写sql的文件

    private static String MAPPERXMLPATH = "mapper/*.xml";   

    private static String SQLSESSIONBEAN = "sqlSessionFactoryBean";

    /**     * 配置数据源      先去jdbc.properties里扫描 然后进行配置     * @return     */

    @Bean(name = "sqlSessionFactory")

    public  SqlSessionFactory sqlSessionFactoryBean(             @Value("${jdbc.url}")String url,

    @Value("${jdbc.user}")String username,             @Value("${jdbc.password}")String password) {

        SqlSessionFactoryBean sqlSessionFactory = new        SqlSessionFactoryBean();

    try {

    DruidDataSource dataSource = new DruidDataSource();             dataSource.setUrl(url);             dataSource.setUsername(username);             dataSource.setPassword(password);             this.dataSource = dataSource;             sqlSessionFactory.setDataSource(dataSource);             //设置mybatis             sqlSessionFactory.setConfigLocation(new ClassPathResource(Mybatis_Config));             //设置模型类别名             sqlSessionFactory.setTypeAliasesPackage(ALIASMODEL);             //配置分页插件             PageHelper pageHelper = new PageHelper();             Properties properties = new Properties();             properties.setProperty("dialect","mysql");             properties.setProperty("offsetAsPageNum","true");             properties.setProperty("rowBoundsWithCount","true");             properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页             properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页             properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数             pageHelper.setProperties(properties);             sqlSessionFactory.setPlugins(new Interceptor[]{pageHelper});             //添加XML目录             ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();             //*.mapper.xml的地址(根据你的项目自行修改)             sqlSessionFactory.setMapperLocations(resolver.getResources(MAPPERXMLPATH));             //设置mapper sql文件的扫描路径             return sqlSessionFactory.getObject();

    } catch (Exception e) {

    e.printStackTrace();             return null;

    }

    }

    /**     * 配置数据模板     * @param sqlSessionFactory     * @return     */

    @Bean     public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){         return new SqlSessionTemplate(sqlSessionFactory);     }     /**     * Spring整合Mapper     * @return     */

    @Bean     public MapperScannerConfigurer getMapperScannerConfigurer(){     MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();         mapperScannerConfigurer.setSqlSessionFactoryBeanName(SQLSESSIONBEAN);         //*.mapper(*.dao)的包名(根据你的项目自行修改)         mapperScannerConfigurer.setBasePackage(MAPPERPATH);         //配置通用Mapper,详情请查阅官方文档         Properties properties = new Properties();         //tk.mybatis.mapper.common.Mapper         properties.setProperty("mappers", "tk.mybatis.mapper.common.Mapper");         properties.setProperty("notEmpty", "false");//insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != ''         //使用的数据库类型名称(MySQL,Oracle,Postgresql...)         properties.setProperty("IDENTITY", "MySQL");//         mapperScannerConfigurer.setProperties(properties);         return mapperScannerConfigurer;     }        /**     * 事务的控制管理  将数据源注入事务内     * @return     */

    @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }好了,业务层的配置完了,简单吧!!!嘿嘿嘿,其实这个和spring的applicationContext.xml配置完全是一样的,我们都知道 Spring最大的特性就是  IOC和AOP,因此只需要将以前配置的bean的class拿到,然后用bean的特定实现类进行set其配置就哦了!!!web Controller层也是一样的。无非是照猫画虎,照鸡画猴下来,我直接贴代码吧!

    import java.util.ArrayList; import java.util.List; @Configuration public class WebMvcConfig {

    //配置视图解析器

    @Bean     public ViewResolver viewResolver(){         InternalResourceViewResolver resolver = new InternalResourceViewResolver();         resolver.setPrefix("/WEB-INF/view/");         resolver.setSuffix(".ftl");         resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);         return resolver;     }

    //上传文件配置

    @Bean(name = "multipartResolver")

    public CommonsFileUploadSupport commonsFileUploadSupport(){         CommonsFileUploadSupport resolver = new CommonsMultipartResolver();         resolver.setMaxInMemorySize(40960);         resolver.setMaxUploadSize(10485760000L);         return resolver;

    }

    //异常解析拦截器  过滤

    @Bean

    public HandlerInterceptor interceptor(){         HandlerInterceptor interceptor = new ExceptionInterceptor();         List interceptors = new ArrayList<>();         MappedInterceptor mappedInterceptor = new MappedInterceptor(new String []{                 "/js/**","/image/**","/uplaod/**","/**/*.jpeg","/**/*.jpg"                 ,"/**/*.gif","/**/*.svg","/**/*.html"         },interceptor);         interceptors.add(mappedInterceptor);         return interceptor;     } }有没有和SpringMVC的配置文件一样?可以和以前的SpringMVC的配置来对比一下,下面我贴上SpringMVC的配置XML文件  大家来对比看看哈~~                                                                                                                                                                                                                                                                     有没有一种照鸡画猴的感觉,嘿嘿,至于其它的注解配置,都和Spring一样的。Controller 层 加上@Controller  Service 加上@Service 注意:Mapper 层要加上 @Mapper 注:转载请注明出处;原文链接:http://www.cnblogs.com/ChoviWu/p/8180022.html

    简书上排版可能不是很好,如果想了解可以点我的博客园链接

    相关文章

      网友评论

          本文标题:SpringBoot无XML配置

          本文链接:https://www.haomeiwen.com/subject/jipcnxtx.html