首页 > 其他分享 >Spring Boot(一)

Spring Boot(一)

时间:2022-10-19 20:34:34浏览次数:36  
标签:Spring Boot druid springframework class import org public

为什么用Spring Boot,这个和.net 太相似了(配置方面啊),不用配置。

Spring Boot(一)_apache

Spring Boot(一)_java_02

Spring Boot(一)_spring_03

Spring Boot(一)_java_04

Spring Boot(一)_apache_05

 

创建方式:

Spring Boot(一)_spring_06

项目结构:

 

Spring Boot(一)_java_07

Spring Boot目录结构:

Spring Boot(一)_java_08

 打印日志的测试,内嵌容器。

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:

替换成

Spring Boot(一)_apache_09

这个替换成上面的

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

  修改端口:

Spring Boot(一)_spring_10

 

Spring Boot(一)_apache_11

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>

  这个地方是分层:

Spring Boot(一)_apache_12

配置 :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/*");
}
}

  

Spring Boot(一)_spring_13

 整合freemarke步骤

Spring Boot(一)_apache_14

 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

  

Spring Boot(一)_apache_15

Spring Boot(一)_java_16

Spring Boot(一)_java_17

Spring Boot(一)_apache_18

<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;
}

  

Spring Boot(一)_apache_19

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 ,其他更恶心。说多了,都是泪,(不过其他一些还是挺好的,如线程和数据结构)一下午,就搞了个搭建开发环境。还得继续往下啊。



标签:Spring,Boot,druid,springframework,class,import,org,public
From: https://blog.51cto.com/u_10999550/5776570

相关文章

  • spring整合mybatis
         ......
  • Springboot项目的全局异常处理类
    在controller的同级目录exception下新建一个JavaClass文件,命名为GlobalExceptionHandler,内容如下packagecn.smxy.stest2022101601.exception;importorg.springframe......
  • springBoot 总结
        这是标准创建boot工程的方式 注意这里使用的是阿里云的url  https://start.aliyun.com/修改服务器端口  自动提示功能消失解决方案    ......
  • springboot + mybatisplus出现was not registered for synchronization because synch
    原因一:缺少事务注解,底层mybatisplus的接口方法有事务原因二:该服务器被限制访问要连接的数据库原因三:乐观锁失效乐观锁由@version注解标注,有以下使用要求支持的......
  • spring-事务概述
    目录​​Spring事务架构​​​​事务特性​​​​并发事务下存在的几个安全性问题​​​​脏读​​​​不可重复读​​​​幻读​​​​事务的隔离级别​​​​事务传播特性......
  • 企业级低代码平台Jeecgboot3.4.2及3.4.3版本新功能介绍
    近期Jeecgboot新发布的3.4.2版本和3.4.3版本做了很多优化,也升级了很多新功能,下面就让我们来看一下都有哪些改变吧。3.4.2版本新功能:一、升级ant-design-vue到3.2.12版......
  • 怎么在uboot下使用通用GPIO接口
    一:在uboot下的defconfig打开如下配置CONFIG_DM=yCONFIG_DM_GPIO=yCONFIG_DWAPB_GPIO=yCONFIG_CMD_GPIO=y二:重新编译u-boot后会生成cmd:gpio在板端执行"gpiostat......
  • uboot环境变量
    zynqmpuboot2020.1环境变量初始化流程先要设置环境变量的存储位置,否则uboot没有saveenv命令运行petalinux-config-cu-boot,如果是单独编译uboot则用makeARCH=arm64......
  • SpringBoot 启动参数及vm参数获取
    @AutowiredprivateApplicationArgumentsapplicationArguments;@AutowiredprivateApplicationContextapplicationContext;main方法通过Appl......
  • Spring Boot 中实现跨域的 5 种方式
    一、为什么会出现跨域问题出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能......