为什么用Spring Boot,这个和.net 太相似了(配置方面啊),不用配置。
创建方式:
项目结构:
Spring Boot目录结构:
打印日志的测试,内嵌容器。
import org.slf4j.LoggerFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class LogFilter implements Filter {
private Logger logger = LoggerFactory.getLogger(LogFilter.class);
public void init(FilterConfig filterConfig) throws ServletException{
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)throws IOException, ServletException {
logger.info("Request--coming");
chain.doFilter(request, response);
}
public void destroy() {
}
}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import java.util.ArrayList;
import java.util.List;
public class FilterBeanConfig {
/**
* 1.构造filter
* 2.配置拦截urlPattern
* 3.利用FilterRegistrationBean进行包装
* @return
*/
@Bean
public FilterRegistrationBean logFilter(){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
filterRegistrationBean.setFilter(new LogFilter());
List<String> urList=new ArrayList<>();
urList.add("*");
filterRegistrationBean.setUrlPatterns(urList);
return filterRegistrationBean;
}
}
将内嵌容器替换成jetty:
替换成
这个替换成上面的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
修改端口:
mybatis-config.xml中的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 配置关闭缓存 -->
<setting name="cacheEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="REUSE"/>
<!-- 事务超时时间 -->
<setting name="defaultStatementTimeout" value="600"/>
</settings>
<typeAliases>
<typeAlias type="com.mooc.house.common.model.User" alias="user" />
</typeAliases>
<mappers>
<mapper resource="mapper/user.xml" />
</mappers>
</configuration>
这个地方是分层:
配置 :application.properties
spring.druid.driverClassName=com.mysql.jdbc.Driver
spring.druid.url=jdbc:mysql://localhost:3306/user?characterEncoding=UTF-8
spring.druid.username=root
spring.druid.password=sunliyuan123456
#最大连接数
spring.druid.maxActive=30
#最小连接数
spring.druid.minIdle=5
#获取连接的最大等待时间
spring.druid.maxWait=10000
#解决mysql8小时问题
spring.druid.validationQuery=SELECT 'x'
#空闲连接检查时间间隔
spring.druid.timeBetweenEvictionRunsMillis=60000
#空间连接最小空闲时间
spring.druid.minEvictableIdleTimeMillis=3000000
pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.13</version>
</dependency>
import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.google.common.collect.Lists;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletRegistration;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.druid")
@Bean(initMethod = "init",destroyMethod = "close")
public DruidDataSource dataSource(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setProxyFilters(Lists.newArrayList(startFilter()));
return dataSource;
}
@Bean
public Filter startFilter(){
StatFilter filter=new StatFilter();
filter.setSlowSqlMillis(5000);
filter.setLogSlowSql(true);
filter.setMergeSql(true);
return filter;
}
@Bean
public ServletRegistrationBean servletRegistration(){
return new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
}
}
整合freemarke步骤
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.http.client.HttpClient;
@Configuration
@ConditionalOnClass({HttpClient.class})
@EnableConfigurationProperties(HttpClientProperties.class)
public class HttpClientAutoConfiguration {
private final HttpClientProperties properties;
public HttpClientAutoConfiguration(HttpClientProperties properties){
this.properties=properties;
}
//httpclient bean 的定義
@Bean
@ConditionalOnMissingBean(HttpClient.class)
public HttpClient httpClient(){
//构造requestConfig
RequestConfig requestConfig=RequestConfig.custom()
.setConnectTimeout(properties.getConnectTimeOut()).setSocketTimeout(properties.getSocketTimeOut()).build();
HttpClient client= (HttpClient) HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setUserAgent(properties.getAgent())
.setMaxConnPerRoute(properties.getMaxConnPerRoute()).setConnectionReuseStrategy(new NoConnectionReuseStrategy());
return client;
}
}
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix="spring.httpclient")
public class HttpClientProperties {
private Integer connectTimeOut=1000;
private Integer socketTimeOut=10000;
public Integer getConnectTimeOut() {
return connectTimeOut;
}
public void setConnectTimeOut(Integer connectTimeOut) {
this.connectTimeOut = connectTimeOut;
}
public Integer getSocketTimeOut() {
return socketTimeOut;
}
public void setSocketTimeOut(Integer socketTimeOut) {
this.socketTimeOut = socketTimeOut;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public Integer getMaxConnPerRoute() {
return maxConnPerRoute;
}
public void setMaxConnPerRoute(Integer maxConnPerRoute) {
this.maxConnPerRoute = maxConnPerRoute;
}
public Integer getMaxConnTotaol() {
return maxConnTotaol;
}
public void setMaxConnTotaol(Integer maxConnTotaol) {
this.maxConnTotaol = maxConnTotaol;
}
private String agent="agent";
private Integer maxConnPerRoute=10;
private Integer maxConnTotaol=50;
}
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class Errorhandler {
private static final Logger logger = LoggerFactory.getLogger(Errorhandler.class);
@ExceptionHandler(value={Exception.class,RuntimeException.class})
public String error500(HttpServletRequest request,Exception e){
logger.error(e.getMessage(),e);
logger.error(request.getRequestURL() + " encounter 500");
return "error/500";
}
}
最后总结一句:不知道java 为什么能在中国这么火,难道就是配置,让中国的程序员这么迷恋他,比起.net,java 最难搞的就是配置,这还是spring Boot ,其他更恶心。说多了,都是泪,(不过其他一些还是挺好的,如线程和数据结构)一下午,就搞了个搭建开发环境。还得继续往下啊。