springboot

springboot 基本配置

换banner
在resources下新建banner.txt,重启即可
热部署
在新建项目的时候
在这里插入图片描述
或者在pom文件中添加依赖

		<dependency>
		//热部署
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
        //快速开发
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

1、pom

pom.xml

  • spring-boot-dependencies:核心依赖在父工程中
  • 我们再写springboot依赖的时候,不需要指定版本,是因为有这些版本仓库

启动器

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

1、启动器说白了就是springboot的启动场景
2、比如spring-boot-starter-web ,他会帮我们自动导入web环境所有的依赖
3、spring-boot会将所有的功能场景都变成一个个的启动器
4、如果我们需要什么功能,只需要找到对应的启动器

主程序

//标注这个类是一个springboot应用
@SpringBootApplication
public class HelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }
}

注解:

@SpringBootConfiguration springboot的配置   就是将启动类作为组件加入到IOC容器
	@Configuration spring的配置类  
		@Component spring的组件
@EnableAutoConfiguration  自动导入配置
	@AutoConfigurationPackage 自动配置包
		@Import(AutoConfigurationPackages.Registrar.class) 自动配置“包注册”
	@Import(AutoConfigurationImportSelector.class)自动配置导入选择
		List<String> configurations = 
		getCandidateConfigurations(annotationMetadata, attributes); 获取所有的配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

META-INF/spring.factories :自动配置的核心文件
在这里插入图片描述
在这里插入图片描述
结论:所有的自动配置都是在启动的时候扫描并加载:spring.factories,所有的自动配置类都在这里,但不一定生效,要判断条件是否成立,只要导入了对应的start就有对应的启动器,有了启动器,自动装配就会生效,然后就配置成功了

  1. springboot在启动的时候,从类路径下,/META-INF/spring.factories获取指定的值

  2. 将这些自动配置类导入容器,自动配置类就会生效,帮我们进行自动配置

  3. 以前我们需要配置的东西,springboot帮我们做了

  4. 整合JavaEE,解决的方案都在spring-boot-autoconfigure-2.3.4.RELEASE.jar这个包下
    在这里插入图片描述

  5. 这个包会把所有需要导入的组件以类名的方式返回,这些组件就会被添加到容器

  6. 容器中也会存在非常多的xxxxautoConfiguration文件,就是这些类会给容器中导入了这个场景需要的所有组件,并自动配置

  7. 有了自动配置类,就免去了我们手动配置的工作

2、主启动类运行

SpringApplication.run(HelloworldApplication.class, args);

SpringApplication :这个类主要做了四件事情

  1. 推断应用的类型是普通项目还是web项目
  2. 查找并加载所有可用的初始化器,设置到initializers属性中
  3. 找出所有的应用程序监听器,设置到listeners属性中
  4. 推断并设置main方法的定义类,找到运行的主类

3、yaml语法

基本语法:

#可以注入到我们的配置类中
#普通的key-value
name: wanghan
#对象
student:
  name: wanghan
  age: 3
#行内写法
student1: {name: wanghan,age: 3}
#数组
pets1:
  - cat
  - dog
  - pig
#数组的行内写法
pets2: [cat,dog,pig]
yaml可以给实体类赋值

通过@ConfigurationProperties(prefix = “person”)

#给实体类赋值
person:
  last-name: wanghan${random.uuid}
  age: ${random.int}
  happy: false
  birth: 2019/12/20
  maps: {k1: v1,k2: v2}
  list:
    - code
    - music
    - girl
  hello: aa
  dog:
    name: ${person.hello:hello}wangcai  #如果person.hello有这个属性,就用这个属性值,如果没有就用:后面的hello
    age: 5
@Component
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> list;
    private Dog dog;

}
通过properties给实体类赋值
@Component
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
//加载指定的配置
@PropertySource(value = "calsspath:person.properties")
public class Person {
	//SPEL表达式去除配置文件的值
    @Value("${name}")
    private String name;
    @Value("${age}")
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> list;
    private Dog dog;
}

两种方式的区别在这里插入图片描述
松散绑定
yml中
last-name 、last-Name
与 person中
lastName、last_Name属性
可以随便对应

JSP303数据校验

1、需要pom中导入spring-boot-starter-validation启动器
2、在实体类中开启注解@Validated
3、在属性上加对应的数据校验注解

@Validated//数据校验
public class Person {
    @Email
    private String name;
    private Integer age;
   
}

在这里插入图片描述

4、配置位置优先级

(加载优先级依次降低)
1、file:/config/ 项目根目录下的config文件夹 (项目名称下新建为项目根目录)
2、file:/ 项目根目录下
3、classpath:/config/ classpath下的config文件夹
4、classpath:/ classpath下

在这里插入图片描述

5、多环境配置

方式一
在这里插入图片描述
在application.yml文件中设置

#springboot的多环境配置
spring:
  profiles:
    active: test

方式二:
通过三个横杠—

#springboot的多环境配置
server:
  port: 8080
spring:
  profiles:
    active: dev
---
server:
  port: 8081
spring:
  profiles: test

---
server:
  port: 8082
spring:
  profiles: dev

6、自动装配的理解

spring.factories中的DataSourceAutoConfiguration配置类为例:在这里插入图片描述
在此配置类中,根据自动加载配置注解,加载DataSourceProperties类在这里插入图片描述

DataSourceProperties类根据yml中的配置赋值,达到自动装配的目的在这里插入图片描述
底层中注解扩展@Conditional在这里插入图片描述
配置文件中能配置的属性都有一个固定的规律

xxxAutoConfiguration (自动装配有默认值),xxxProperties 和 配置文件绑定 就可以使用自定义的配置了

自动装配的原理:

  1. SpringBoot启动会加载大量的自动配置类
  2. 我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中
  3. 我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在其中,我们就不需要再手动的配置)
  4. 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性,我们只需要再配置文件中指定这些属性的值即可
    xxxAutoConfiguration:自动配置类;给容器添加组件
    xxxProperties:封装配置文件中相关属性;

springboot自动配置原理(自己总结的重点):

  1. 启动类上的注解@SpringBootApplication
  2. 父类中的启动自动配置注解@EnableAutoConfiguration
  3. 父类中的@Import(AutoConfigurationImportSelector.class)自动配置选择器的类
  4. 选择器类中去寻找spring.factories,里面有springboot中的各种自动配置类
  5. 自动配置类上的@Conditional条件注解,会根据条件去判断自身的自动配置类生不生效
  6. 如果在pom文件中没有导入对应的启动器,即没有对应的类,则此启动器的自动配置类不生效
  7. 启动的时候,会加载各个自动配置类
  8. 自动配置类上都有加载自身的一个xxxProperties的类
  9. xxxProperties的类通过注解@@ConfigurationProperties(prefix = “spring.http”)跟配置文件绑定
    10.各个配置类都会有默认配置,如果在配置文件中,配置了属性值之后就可以用自定义的配置了

查看各种配置类启动评估报告

yml中配置
debug:true
启动可以查看各种配置类启动评估报告
在这里插入图片描述
Positive matches:已经开启的
Negative matches:没有生效的
在这里插入图片描述

springboot web开发

web开发要解决的问题:

  • 导入静态资源
  • 首页
  • jsp,模板引擎Thymeleaf
  • 装配扩展springMVC
  • 增删改查
  • 拦截器
  • 国际化
  • List item

1、导入静态资源问题

默认的静态资源访问路径

第一种方式:引入依赖的方式引入静态资源
  1. 在webjars官网找到jquery的依赖坐标,添加到pom文件的依赖中
  2. 访问静态资源的路径为/webjars/* 例如:http://localhost:8080/webjars/jquery/3.5.1/jquery.js
    在这里插入图片描述
第二种方式:在默认的静态资源路径添加静态资源
		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			//有自定义配置则失效
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))				.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}
	private String staticPathPattern = "/**";
	private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

如果没有自定义静态资源路径,则使用默认的路径
访问路径为/**
静态资源的存储路径为:
“classpath:/META-INF/resources/",
“classpath:/resources/”,
“classpath:/static/”,
"classpath:/public/
如果这四个路径中都有名称为1.js的文件,则默认的访问优先级别从高到低

自定义静态资源路径

properties或yaml配置文件中配置,则默认的静态资源路径失效(最好不要用)

spring.mvc.static-path-pattern=/hello/

总结:在springboot中我们可以使用以下方式处理静态资源

2、首页和图标定制

与静态资源类似,将index.html放入静态资源类中,识别到index.html就会作为首页,程序启动时调用首页

3、thymeleaf模板引擎

thymeleaf导入

1、导入对应的thymeleaf启动器: spring-boot-starter-thymeleaf
自动配置类属性默认的访问html路径为:classpath:/templates/
在这里插入图片描述
2、在html页面头导入约束

<html lang="en" xmlns:th="http://www.thymeleaf.org">

thymeleaf语法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<h1>首页</h1>

<!--所有的html元素都可以被 thymeleaf 接管替换: th:元素名-->
<div th:text="${msg}"></div>  <!--不转义-->
<div th:utext="${msg}"></div> <!--转义-->
<hr>
<h1 th:each="user:${list}" th:text="${user}"></h1>  <!--for循环 建议使用-->
<hr>
<h1 th:each="user:${list}" >[[${user}]]</h1>   <!--for循环-->
</body>
</html>

3、springMVC配置原理

配置原理

  1. 容器中存在很多的xxxConfiguraton接口,这些接口可以方便我们扩展配置,扩展的配置与xxxAutoConfiguration的配置可以共同生效
  2. 如果想要全面接管配置,则只要让自动配置类xxxAutoConfiguration上的@Conditional注解不满足条件即可
  3. xxxAutoConfiguration生效是由注解@Conditional决定的,如果满足条件,则xxxAutoConfiguration自动配置类生效,如果不满足则xxxConfiguraton的实现类生效

例如:mvcConfiguration的扩展

//全面扩展springMVC
//如果你想diy一些定制化的功能,只要写这个组件,然后将他交给springboot容器
@Configuration
@EnableWebMvc  //如果全面接管mvc的配置则开启@EnableWebMvc注解
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/aaa").setViewName("index");
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)//这个类继承了 WebMvcConfigurationSupport
public @interface EnableWebMvc {
}
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {}
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)  //
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

1、看源码可以很清楚的知道,WebMvcAutoConfiguration 的失效条件是容器中存在WebMvcConfigurationSupport类
2、当开启扩展配置类MyMvcConfig 中开启@EnableWebMvc注解,则间接的继承了WebMvcConfigurationSupport 类
3、满足容器中存在WebMvcConfigurationSupport 的条件,所以
WebMvcAutoConfiguration 自动配置会失效

springMVC扩展方式
方式一:重写 WebMvcConfigurer 的方法,扩展springMVC方法
方式二:自定义webMVC组件实现类,注入到spring容器中,使WebMvcAutoConfiguration自动配置中的组件失效

//全面扩展springMVC
//如果你想diy一些定制化的功能,只要写这个组件,然后将他交给springboot容器
@Configuration
//@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
    //方式一:重写 WebMvcConfigurer下的方法
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/aaa").setViewName("index");
    }

    //方式二:继承 MVC 中组件的接口,将实现类加入到 IOC 容器中
    public static class MyViewResolver implements ViewResolver{
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
    @Bean
    public ViewResolver getViewResolver(){
        return new MyViewResolver();
    }
}

首页配置

MVC配置首页访问路径,重写WebMvcConfig下的addViewControllers方法

@Configuration
//@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
    //方式一:重写 WebMvcConfigurer下的方法
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index").setViewName("index");
    } 
}

页面国际化

  1. 我们需要配置i18n文件
    在这里插入图片描述
#spring 信息配置
spring.messages.basename=i18n.login
  1. 按钮切换中英文,携带参数访问首页
 <a class="btn btn-sm" th:href="@{/index.html(l=zh_CN)}">中文</a>  //发送请求访问首页,附带参数判断国际化
 <a class="btn btn-sm" th:href="@{/index.html(l=en_US)}">English</a>
  1. 自定义组件LocalResolver,将组件配置到容器中(方法名即bean的名字,必须与localeResolver一致,否则解析器不生效)
    自定义 LocaleResolver(本地解析)组件实现类
public class MyLocalResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String languge = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(languge)){
            String[] split = languge.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
}

将自定义本地解析器,注入到ioc容器
注意,bean 的名字一定要是localeResolver

@Configuration
//@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
    //方式一:重写 WebMvcConfigurer下的方法
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
    //自定义国际化,注入bean时方法名即bean的名字,一定为localeResolver,否则无效
    @Bean
    public static LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }
}
  1. htlm页面中使用 #{ } 取出对应的国际化内容
 <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>   //取国际化内容
 <input type="checkbox" value="remember-me">[[#{login.remember}]]  取国际化内容

原理分析:
WebMvcAutoConfiguration下的 localeResolver方法

		@Bean
		@ConditionalOnMissingBean
		@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
		public LocaleResolver localeResolver() {
			if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
				return new FixedLocaleResolver(this.mvcProperties.getLocale());
			}
			AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
			localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
			return localeResolver;
		}

如果我们自定义LocaleResolver,并将自定义的LocaleResolver注入到容器中,(注意注入容器时bean 的名字一定要是localeResolver),此时Springboot自动配置中的LocaleResolver上的@ConditionalOnMissingBean会判断容器中是否有一个相同的bean,如果有则该注解下的bean不生效,自定义的bean会生效
所以自定义的本地解析器,注入bean的时候,bean的名字一定要跟springboot源码中的名字保持一致,即localeResolver

springboot整合

1、整合JDBC

  • 导包,jdbc 和mysql驱动的包
 		<dependency>	
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
  • yml配置数据源属性
spring:
  datasource:
    username: root
    password: root
    #加入报错了,就加入一个时区的参数 servierTimezone=UTC
    url: jdbc:mysql://192.168.168.132:3306/test?servierTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
  • xxxxTemplate:springboot已经配置好的bean,拿来即用,例如JDBC、redis
@RestController
public class JdbcController {

    //XXXTemplate:springboot已经配置好的bean,拿来即用,例如JDBC、redis
    @Autowired
    JdbcTemplate jdbcTemplate;
    @RequestMapping("/query")
    public List<Map<String,Object>> query(){
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    @RequestMapping("/update/{id}")
    public String query(@PathVariable("id")int id){
        String sql = "update test.user set name = ? ,pwd = ? where id ="+id;
        Object[] objects = new Object[2];
        objects[0]="hahahha";
        objects[1]="33333";
        jdbcTemplate.update(sql,objects);
        return "修改成功";
    }
}

2、整合Druid

  • 导包 druid的包, //因为druid自带sql日志记录功能,所以需要导入log4j的包
 		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        //因为druid自带sql日志记录功能,所以需要导入log4j的包
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
  • 编写druid配置文件,原理:当ioc容器中有dataSource,则默认配置的DataSource失效
@Configuration
public class DruidConfig {
   @ConfigurationProperties(prefix = "spring.datasource")
   @Bean
   public DataSource druidDataSource() {
       return new DruidDataSource();
   }
}
  • 配置yml文件
spring:
  datasource:
    username: root
    password: root
    #加入报错了,就加入一个时区的参数 servierTimezone=UTC
    url: jdbc:mysql://192.168.168.132:3306/test?servierTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
	type: com.alibaba.druid.pool.DruidDataSource
	
    initial-size: 10 # 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
    min-idle: 10 # 最小连接池数量
    maxActive: 200 # 最大连接池数量
    maxWait: 60000 # 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置
    timeBetweenEvictionRunsMillis: 60000 # 关闭空闲连接的检测时间间隔.Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接。
    minEvictableIdleTimeMillis: 300000 # 连接的最小生存时间.连接保持空闲而不被驱逐的最小时间
    validationQuery: SELECT 1 FROM DUAL # 验证数据库服务可用性的sql.用来检测连接是否有效的sql 因数据库方言而差, 例如 oracle 应该写成 SELECT 1 FROM DUAL
    testWhileIdle: true # 申请连接时检测空闲时间,根据空闲时间再检测连接是否有效.建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRun
    testOnBorrow: false # 申请连接时直接检测连接是否有效.申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnReturn: false # 归还连接时检测连接是否有效.归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    poolPreparedStatements: true # 开启PSCache
    maxPoolPreparedStatementPerConnectionSize: 20 #设置PSCache值
    connectionErrorRetryAttempts: 3 # 连接出错后再尝试连接三次
    breakAfterAcquireFailure: true # 数据库服务宕机自动重连机制
    timeBetweenConnectErrorMillis: 300000 # 连接出错后重试时间间隔
    asyncInit: true # 异步初始化策略
    remove-abandoned: true # 是否自动回收超时连接
    remove-abandoned-timeout: 1800 # 超时时间(以秒数为单位)
    transaction-query-timeout: 6000 # 事务超时时间
    filters: stat,wall,log4j2 #stat监控统计、wall防止sql注入、log4j2日志记录
    connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
    web-stat-filter:
      enabled: true
      url-pattern: "/*"
      exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
    stat-view-servlet:
      url-pattern: "/druid/*"
      allow:
      deny:
      reset-enable: false
      login-username: admin
      login-password: admin
  • xxxxTemplate:springboot已经配置好的bean,拿来即用,例如JDBC、redis
@RestController
public class JdbcController {

    //XXXTemplate:springboot已经配置好的bean,拿来即用,例如JDBC、redis
    @Autowired
    JdbcTemplate jdbcTemplate;
    @RequestMapping("/query")
    public List<Map<String,Object>> query(){
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    @RequestMapping("/update/{id}")
    public String query(@PathVariable("id")int id){
        String sql = "update test.user set name = ? ,pwd = ? where id ="+id;
        Object[] objects = new Object[2];
        objects[0]="hahahha";
        objects[1]="33333";
        jdbcTemplate.update(sql,objects);
        return "修改成功";
    }
}

Druid扩展:
1、druid自带可视化后台监控
2、springboot内置了servlet容器,所以没有web.xml,替代方法:ServletRegistrationBean
3、filer替代方法同servlet

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
    //因为springboot内置了servlet容器,所以没有web.xml,替代方法:ServletRegistrationBean
    @Bean   //配置访问 druid 后台监控的servlet
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");//配置访问路径
        //后台需要有人登陆,账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();
        //配置
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");
        //允许谁访问
        initParameters.put("allow", "");
        //不允许谁访问
//        initParameters.put("wanghan", "192.168.168.132");
        //设置初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }

    //配置filter过滤器
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParameters = new HashMap<>();
        //这些东西不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        return bean;
    }
}

3、整合mybatis

  • 导包,除了导入jdbc和mysql驱动的包之外,还需要导入mybatis针对springboot做的适配的包
		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
  • 编写mapper.xml文件,mapper接口注入ioc @Mapper,并声明命名空间
  • yml文件配置别名和xml加载地址
spring:
  datasource:
    username: root
    password: root
    #加入报错了,就加入一个时区的参数 servierTimezone=UTC
    url: jdbc:mysql://192.168.168.132:3306/test?servierTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.kuang.pojo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值