在前兩天,Damon也是將springboot大概的狀況給大家介紹了不少,今天Damon就跟大家說說springboot框架的一些整合,以及一些實用的插件介紹,希望大家喜歡。(最近由于實訓(xùn)比較累【現(xiàn)在才10已經(jīng)很目澀了】,所以每日推薦也是比較慢,希望大家原諒。)
Spring Boot 集成druid
druid有很多個配置選項,使用Spring Boot 的配置文件可以方便的配置druid。
在application.yml配置文件中寫上:
spring: datasource: name: test url: jdbc:mysql://192.168.16.137:3306/test username: root password: # 使用druid數(shù)據(jù)源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20這里通過type: com.alibaba.druid.pool.DruidDataSource配置即可!
Spring Boot 集成MyBatis
- Spring Boot 集成MyBatis有兩種方式,一種簡單的方式就是使用MyBatis官方提供的:
mybatis-spring-boot-starter - 另外一種方式就是仍然用類似mybatis-spring的配置方式,這種方式需要自己寫一些代碼,但是可以很方便的控制MyBatis的各項配置。
mybatis-spring-boot-starter方式
-
在pom.xml中添加依賴:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version></dependency>
mybatis-spring-boot-starter依賴樹如下:
其中mybatis使用的3.3.0版本,可以通過:
- <mybatis.version>3.3.0</mybatis.version>屬性修改默認版本。
- mybatis-spring使用版本1.2.3,可以通過:
- <mybatis-spring.version>1.2.3</mybatis-spring.version>修改默認版本。
在application.yml中增加配置:
mybatis:
mapperLocations: classpath:mapper/*.xml
typeAliasesPackage: tk.mapper.model除了上面常見的兩項配置,還有:
- mybatis.config:mybatis-config.xml配置文件的路徑
- mybatis.typeHandlersPackage:掃描typeHandlers的包
- mybatis.checkConfigLocation:檢查配置文件是否存在
- mybatis.executorType:設(shè)置執(zhí)行模式(SIMPLE, REUSE, BATCH),默認為SIMPLE
mybatis-spring方式
這種方式和平常的用法比較接近。需要添加mybatis依賴和mybatis-spring依賴。
-
然后創(chuàng)建一個MyBatisConfig配置類:
/** * MyBatis基礎(chǔ)配置 * * @author liuzh * @since 2015-12-19 10:11 */ @Configuration @EnableTransactionManagement public class MyBatisConfig implements TransactionManagementConfigurer { @Autowired DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setTypeAliasesPackage("tk.mybatis.springboot.model"); //分頁插件 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("reasonable", "true"); properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("returnPageInfo", "check"); properties.setProperty("params", "count=countSql"); pageHelper.setProperties(properties); //添加插件 bean.setPlugins(new Interceptor[]{pageHelper}); //添加XML目錄 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); }}
上面代碼創(chuàng)建了一個SqlSessionFactory和一個SqlSessionTemplate,為了支持注解事務(wù),增加了@EnableTransactionManagement注解,并且反回了一個PlatformTransactionManagerBean。
-
另外應(yīng)該注意到這個配置中沒有MapperScannerConfigurer,如果我們想要掃描MyBatis的Mapper接口,我們就需要配置這個類,這個配置我們需要單獨放到一個類中。
/** * MyBatis掃描接口 * * @author liuzh * @since 2015-12-19 14:46 */ @Configuration //注意,由于MapperScannerConfigurer執(zhí)行的比較早,所以必須有下面的注解 @AutoConfigureAfter(MyBatisConfig.class) public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper"); //配置通用mappers Properties properties = new Properties(); properties.setProperty("mappers", "tk.mybatis.springboot.util.MyMapper"); properties.setProperty("notEmpty", "false"); properties.setProperty("IDENTITY", "MYSQL"); //這里使用的通用Mapper的MapperScannerConfigurer,所有有下面這個方法 mapperScannerConfigurer.setProperties(properties); return mapperScannerConfigurer; } } 這個配置一定要注意@AutoConfigureAfter(MyBatisConfig.class),必須有這個配置,否則會有異常。原因就是這個類執(zhí)行的比較早,由于sqlSessionFactory還不存在,后續(xù)執(zhí)行出錯。做好上面配置以后就可以使用MyBatis了。
關(guān)于分頁插件和通用Mapper集成
- 分頁插件作為插件的例子在上面代碼中有。
- 通用Mapper配置實際就是配置MapperScannerConfigurer的時候使用- tk.mybatis.spring.mapper.MapperScannerConfigurer即可,配置屬性使用Properties。
Spring Boot集成MyBatis的基礎(chǔ)項目
- 分頁插件和通用Mapper的相關(guān)信息可以通過上面地址找到。
Spring Boot 靜態(tài)資源處理
Spring Boot 默認的處理方式就已經(jīng)足夠了,默認情況下Spring Boot 使用WebMvcAutoConfiguration中配置的各種屬性。
建議使用Spring Boot 默認處理方式,需要自己配置的地方可以通過配置文件修改。
-
但是如果你想完全控制Spring MVC,你可以在@Configuration注解的配置類上增加@EnableWebMvc,增加該注解以后WebMvcAutoConfiguration中配置就不會生效,你需要自己來配置需要的每一項。這種情況下的配置方法建議參考WebMvcAutoConfiguration類。
-本文以下內(nèi)容針對Spring Boot 默認的處理方式,部分配置通過在application.yml配置文件中設(shè)置。
-.spring boot默認加載文件的路徑是/META-INF/resources/ /resources/ /static/ /public/ private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; 所有本地的靜態(tài)資源都配置在了classpath下面了, 而非在webapp下了
配置資源映射
- Spring Boot 默認配置的/映射到/static(或/public ,/resources,/META-INF/resources),/webjars/會映射到
- classpath:/META-INF/resources/webjars/。
注意:上面的/static等目錄都是在classpath:下面。
-
如果你想增加如/mystatic/**映射到classpath:/mystatic/,你可以讓你的配置類繼承WebMvcConfigurerAdapter,然后重寫如下方法:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/mystatic/**") .addResourceLocations("classpath:/mystatic/"); }
- 這種方式會在默認的基礎(chǔ)上增加/mystatic/**映射到classpath:/mystatic/,不會影響默認的方式,可以同時使用。
- 靜態(tài)資源映射還有一個配置選項,為了簡單這里用.properties方式書寫:
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
這個配置會影響默認的/,例如修改為/static/后,只能映射如/static/js/sample.js這樣的請求(修改前是/js/sample.js)。這個配置只能寫一個值,不像大多數(shù)可以配置多個用逗號隔開的。
使用注意
-
例如有如下目錄結(jié)構(gòu):
└─resources │ application.yml │ ├─static │ ├─css │ │ index.css │ │ │ └─js │ index.js │ └─templates index.ftl 在index.ftl中該如何引用上面的靜態(tài)資源呢?
如下寫法:
<link rel="stylesheet" type="text/css" href="/css/index.css">
<script type="text/javascript" src="/js/index.js"></script>注意:默認配置的/**映射到/static(或/public ,/resources,/META-INF/resources)
當(dāng)請求/css/index.css的時候,Spring MVC 會在/static/目錄下面找到。
如果配置為/static/css/index.css,那么上面配置的幾個目錄下面都沒有/static目錄,因此會找不到資源文件!
所以寫靜態(tài)資源位置的時候,不要帶上映射的目錄名(如/static/,/public/,/resources/,/META-INF/resources/)!
使用WebJars
WebJars:http://www.webjars.org/
-
例如使用jquery,添加依賴:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.11.3</version>
</dependency> -
然后可以如下使用:
<script type="text/javascript"
src="/webjars/jquery/1.11.3/jquery.js"></script> 你可能注意到href中的1.11.3版本號了,如果僅僅這么使用,那么當(dāng)我們切換版本號的時候還要手動修改href,怪麻煩的,我們可以用如下方式解決。
-
先在pom.xml中添加依賴:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency> -
增加一個WebJarController:
@Controller public class WebJarController { private final WebJarAssetLocator assetLocator = new WebJarAssetLocator(); @ResponseBody @RequestMapping("/webjarslocator/{webjar}/**") public ResponseEntity locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) { try { String mvcPrefix = "/webjarslocator/" + webjar + "/"; String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length())); return new ResponseEntity(new ClassPathResource(fullPath), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } } -
然后使用的時候按照如下方式:
<script
type="text/javascript" src="/webjarslocator/jquery/jquery.js"></script> 注意:這里不需要在寫版本號了,但是注意寫url的時候,只是在原來url基礎(chǔ)上去掉了版本號,其他的都不能少!
靜態(tài)資源版本管理
Spring MVC 提供了靜態(tài)資源版本映射的功能。
用途:當(dāng)我們資源內(nèi)容發(fā)生變化時,由于瀏覽器緩存,用戶本地的靜態(tài)資源還是舊的資源,為了防止這種情況導(dǎo)致的問題,我們可能會手動在請求url的時候加個版本號或者其他方式。
-
版本號如:
<script
type="text/javascript" src="/js/sample.js?v=1.0.1"></script> Spring MVC 提供的功能可以很容易的幫助我們解決類似問題。
Spring MVC 有兩種解決方式。
注意:下面的配置方式針對freemarker模板方式,其他的配置方式可以參考。
資源名-md5 方式
<link rel="stylesheet" type="text/css" href="/css/index-2b371326aa93ce4b611853a309b69b29.css">
- Spring 會自動讀取資源md5,然后添加到index.css的名字后面,因此當(dāng)資源內(nèi)容發(fā)生變化的時候,文件名發(fā)生變化,就會更新本地資源。
- 配置方式:
在application.properties中做如下配置:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**這樣配置后,所有/**請求的靜態(tài)資源都會被處理為上面例子的樣子。
到這兒還沒完,我們在寫資源url的時候還要特殊處理。
首先增加如下配置:
@ControllerAdvice
public class ControllerConfig {
@Autowired
ResourceUrlProvider resourceUrlProvider;
@ModelAttribute("urls")
public ResourceUrlProvider urls() {
return this.resourceUrlProvider;
}
}-
然后在頁面寫的時候用下面的寫法:
<link rel="stylesheet" type="text/css" href="${urls.getForLookupPath('/css/index.css')}">
使用urls.getForLookupPath('/css/index.css')來得到處理后的資源名。
版本號 方式
在application.properties中做如下配置:
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/,/v1.0.0/
spring.resources.chain.strategy.fixed.version=v1.0.0這里配置需要特別注意,將version的值配置在paths中。
-
在頁面寫的時候,寫法如下:
<script
type="text/javascript" src="${urls.getForLookupPath('/js/index.js')}"></script> -
注意,這里仍然使用了urls.getForLookupPath,urls配置方式見上一種方式。
在請求的實際頁面中,會顯示為:<script
type="text/javascript" src="/v1.0.0/js/index.js"></script> 可以看到這里的地址是/v1.0.0/js/index.js。
靜態(tài)資源版本管理 處理過程
- 在Freemarker模板首先會調(diào)用urls.getForLookupPath方法,返回一個/v1.0.0/js/index.js或/css/index-2b371326aa93ce4b611853a309b69b29.css。
- 這時頁面上的內(nèi)容就是處理后的資源地址。這之后瀏覽器發(fā)起請求。
- 這里分開說。
第一種md5方式
- 請求/css/index-2b371326aa93ce4b611853a309b69b29.css,我們md5配置的paths=/**,所以Spring MVC 會嘗試url中是否包含-,如果包含會去掉后面這部分,然后去映射的目錄(如/static/)查找/css/index.css文件,如果能找到就返回。
第二種版本方式
- 請求/v1.0.0/js/index.js。
- 如果我們paths中沒有配置/v1.0.0,那么上面這個請求地址就不會按版本方式來處理,因此會找不到上面的資源。
- 如果配置了/v1.0.0,Spring 就會將/v1.0.0去掉再去找/js/index.js,最終會在/static/下面找到。