SpringBoot,本身研究了好幾天,之前也是沒有接觸過這類的框架,不過原理吧,也就是那麼些個原理,畢竟都是Spring開源下的子框架。css
好了,迴歸正題,今天晚上研究了很久,寫出來了無配置文件的javaConfig配置,Demo集成了SpringMvc + mybatis + boot ,裏面也含有hibernate的core包,用來生成數據庫表結構的。html
首先 ,添加以下boot官方提供的依賴包:java
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.mybatis.spring.boot</groupId> 7 <artifactId>mybatis-spring-boot-starter</artifactId> 8 <version>1.1.1</version> 9 </dependency> 10 <!-- jpa--> 11 <dependency> 12 <groupId>org.springframework.boot</groupId> 13 <artifactId>spring-boot-starter-data-jpa</artifactId> 14 <version>1.5.7.RELEASE</version> 15 </dependency>
上面的就是配置中所須要的架包,由於本demo體現的是無配置文件,因此demo裏不會有什麼配置文件(yaml除外)mysql
我使用的數據源是阿里的Druid 另外還有分頁的架包以及mybatis整合spring的架包git
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
jar包如今已經分配完畢(注意jar包的版本號,我的發現不少問題都出在了jar包衝突或者版本不一致的身上了)
本demo 演示的編輯工具是 IDEA 由於我建立的是springboot項目,因此編輯器會自動給我生成了application.yml
下來我貼上這個內容
server:
port: 8081
context-path: /
#開啓spring AOP配置
aop:
auto: true
proxy-target-class: true
# jpa 配置
# jpa:
# show-sql: true
## open-in-view: true
# hibernate:
# ddl-auto: update
#mybatis:
# type-aliases-package: com.example.model
# mapper-locations: classpath:mapper/*.xml
# configuration:
# use-new-id-generator-mappings:
注:數據源的配置也能夠放在 yml文件裏,也很方便,由於本demo演示的是在javaConfig裏面配置,因此就沒有配置在yml裏面。github
下來建立配置文件(jdbc.properties以及 javaConfig )web
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
這和普通大多數項目的同樣,能夠粘過來!spring
如今,我來開始配置 數據源 以及 業務層配置sql
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<MappedInterceptor> 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文件 你們來對比看看哈~~
<mvc:interceptors> <mvc:interceptor> <!-- 對全部的請求攔截使用/** ,對某個模塊下的請求攔截使用:/myPath/* --> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="/**/*.html" /> <mvc:exclude-mapping path="/**/*.css" /> <mvc:exclude-mapping path="/**/*.js" /> <mvc:exclude-mapping path="/**/*.jpeg" /> <mvc:exclude-mapping path="/**/*.gif" /> <mvc:exclude-mapping path="/**/*.png" /> <mvc:exclude-mapping path="/**/*.eot" /> <mvc:exclude-mapping path="/**/*.otf" /> <mvc:exclude-mapping path="/**/*.svg" /> <mvc:exclude-mapping path="/**/*.ttf" /> <mvc:exclude-mapping path="/**/*.woff" /> <mvc:exclude-mapping path="/**/*.woff2" /> <ref bean="exceptionInterceptor" /> </mvc:interceptor> </mvc:interceptors> <bean name="exceptionInterceptor" class="yf.wuchw.web.ExceptionInterceptor" /> <mvc:default-servlet-handler /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property> <property name="maxInMemorySize" value="40960"></property> </bean> <!--配置jsp顯示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp" /> <property name="suffix" value=".jsp" /> </bean>
有沒有一種照雞畫猴的感受,嘿嘿,至於其它的註解配置,都和Spring同樣的。Controller 層 加上@Controller Service 加上@Service
注意:Mapper 層要加上 @Mapper
注:轉載請註明出處;原文連接:http://www.cnblogs.com/ChoviWu/p/8180022.html