druid有很多个配置选项,使用Spring Boot 的配置文件可以方便的配置druid。
在application.yml配置文件中写上:
spring:
datasource:
name: test
url: jdbc:mysql://192.168.16.137:3306/test
username: root
password:
# 使用druid数据源
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配置即可!
在pom.xml中添加依赖:
mybatis-spring-boot-starter依赖树如下:
其中mybatis使用的3.3.0版本,可以通过:
在application.yml中增加配置:
mybatis: mapperLocations: classpath:mapper/*.xml typeAliasesPackage: tk.mapper.model
除了上面常见的两项配置,还有:
这种方式和平常的用法比较接近。需要添加mybatis依赖和mybatis-spring依赖。
然后创建一个MyBatisConfig配置类:
/**
* MyBatis基础配置
*
* @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);
}
}
复制代码
上面代码创建了一个SqlSessionFactory和一个SqlSessionTemplate,为了支持注解事务,增加了@EnableTransactionManagement注解,并且反回了一个PlatformTransactionManagerBean。
另外应该注意到这个配置中没有MapperScannerConfigurer,如果我们想要扫描MyBatis的Mapper接口,我们就需要配置这个类,这个配置我们需要单独放到一个类中。
/**
* MyBatis扫描接口
*
* @author liuzh
* @since 2015-12-19 14:46
*/
@Configuration
//注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@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),必须有这个配置,否则会有异常。原因就是这个类执行的比较早,由于sqlSessionFactory还不存在,后续执行出错。做好上面配置以后就可以使用MyBatis了。
Spring Boot 默认的处理方式就已经足够了,默认情况下Spring Boot 使用WebMvcAutoConfiguration中配置的各种属性。
建议使用Spring Boot 默认处理方式,需要自己配置的地方可以通过配置文件修改。
但是如果你想完全控制Spring MVC,你可以在@Configuration注解的配置类上增加@EnableWebMvc,增加该注解以后WebMvcAutoConfiguration中配置就不会生效,你需要自己来配置需要的每一项。这种情况下的配置方法建议参考WebMvcAutoConfiguration类。 -本文以下内容针对Spring Boot 默认的处理方式,部分配置通过在application.yml配置文件中设置。 -.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/" };
复制代码
所有本地的静态资源都配置在了classpath下面了, 而非在webapp下了
注意:上面的/static等目录都是在classpath:下面。
如果你想增加如/mystatic/**映射到classpath:/mystatic/,你可以让你的配置类继承WebMvcConfigurerAdapter,然后重写如下方法:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/mystatic/**")
.addResourceLocations("classpath:/mystatic/");
}
复制代码
例如有如下目录结构:
└─resources
│ application.yml
│
├─static
│ ├─css
│ │ index.css
│ │
│ └─js
│ index.js
│
└─templates
index.ftl
复制代码
在index.ftl中该如何引用上面的静态资源呢?
如下写法:
注意:默认配置的/**映射到/static(或/public ,/resources,/META-INF/resources)
当请求/css/index.css的时候,Spring MVC 会在/static/目录下面找到。
如果配置为/static/css/index.css,那么上面配置的几个目录下面都没有/static目录,因此会找不到资源文件!
所以写静态资源位置的时候,不要带上映射的目录名(如/static/,/public/,/resources/,/META-INF/resources/)!
WebJars:www.webjars.org/
例如使用jquery,添加依赖:
org.webjars jquery 1.11.3
然后可以如下使用:
你可能注意到href中的1.11.3版本号了,如果仅仅这么使用,那么当我们切换版本号的时候还要手动修改href,怪麻烦的,我们可以用如下方式解决。
先在pom.xml中添加依赖:
org.webjars webjars-locator
增加一个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);
}
}
}
复制代码
然后使用的时候按照如下方式:
注意:这里不需要在写版本号了,但是注意写url的时候,只是在原来url基础上去掉了版本号,其他的都不能少!
Spring MVC 提供了静态资源版本映射的功能。
用途:当我们资源内容发生变化时,由于浏览器缓存,用户本地的静态资源还是旧的资源,为了防止这种情况导致的问题,我们可能会手动在请求url的时候加个版本号或者其他方式。
版本号如:
Spring MVC 提供的功能可以很容易的帮助我们解决类似问题。
Spring MVC 有两种解决方式。
注意:下面的配置方式针对freemarker模板方式,其他的配置方式可以参考。
<link rel="stylesheet" type="text/css" href="/css/index-2b371326aa93ce4b611853a309b69b29.css"> 复制代码
在application.properties中做如下配置:
spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/**
这样配置后,所有/**请求的静态资源都会被处理为上面例子的样子。
到这儿还没完,我们在写资源url的时候还要特殊处理。
首先增加如下配置:
@ControllerAdvice public class ControllerConfig { @Autowired ResourceUrlProvider resourceUrlProvider; @ModelAttribute("urls") public ResourceUrlProvider urls() { return this.resourceUrlProvider; } }
然后在页面写的时候用下面的写法:
使用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中。
在页面写的时候,写法如下:
注意,这里仍然使用了urls.getForLookupPath,urls配置方式见上一种方式。 在请求的实际页面中,会显示为:
可以看到这里的地址是/v1.0.0/js/index.js。
作为一个新生程序猿,Damon希望能够与大家一同进步。文章或者描述有所不足的地方,希望大家多多提出来,一同进步。
过去文章都上传到github,有兴趣的小伙伴可以Star下: github.com/xxxyyh/Fron…