跳至主要內容

SpringBoot基础总结

Alooc...大约 6 分钟后端框架SpringBootSpringBoot

简介,简单项目配置:

application.yml

spring:
  datasource:
#    url: jdbc:mysql://localhost:3306/db_account
    url: jdbc:mysql://localhost:3306/atguigudb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver


    druid:
      aop-patterns: com.atguigu.admin.*  #springbean监控
      filters: stat,wall,slf4j  #所有开启的功能

      stat-view-servlet:  #监控页配置
        enabled: true
        login-username: admin
        login-password: admin
        resetEnable: false

      web-stat-filter:  #web监控
        enabled: true
        urlPattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'


      filter:
        stat: #sql监控
          slow-sql-millis: 1000
          logSlowSql: true
          enabled: true
        wall: #防火墙
          enabled: true
          config:
            drop-table-allow: false



  redis:
    host: r-bp1nc7reqesxisgxpipd.redis.rds.aliyuncs.com
    port: 6379
    password: lfy:Lfy123456
    client-type: jedis
    jedis:
      pool:
        max-active: 10
  #    url: redis://lfy:Lfy123456@r-bp1nc7reqesxisgxpipd.redis.rds.aliyuncs.com:6379
#    lettuce:
#      pool:
#        max-active: 10
#        min-idle: 5



  #    type: com.zaxxer.hikari.HikariDataSource
  jdbc:
    template:
      query-timeout: 3
  boot:
    admin:
      client:
        url: http://localhost:8888
        instance:
          prefer-ip: true  #使用ip注册进来
  application:
    name: boot-05-web-admin




# 配置mybatis规则、使用MyBatisPlus则此项配置无效
#mybatis:
##  config-location: classpath:mybatis/mybatis-config.xml
#  mapper-locations: classpath:mybatis/mapper/*.xml
#  configuration:  # 指定mybatis全局配置文件中的相关配置项
#    map-underscore-to-camel-case: true


# management 是所有actuator的配置
# management.endpoint.端点名.xxxx  对某个端点的具体配置
management:
  endpoints:
    enabled-by-default: true  #默认开启所有监控端点  true
    web:
      exposure:
        include: '*' # 以web方式暴露所有端点

  endpoint:   #对某个端点的具体配置
    health:
      show-details: always
      enabled: true

    info:
      enabled: true

    beans:
      enabled: true

    metrics:
      enabled: true

info:
  appName: boot-admin
  appVersion: 1.0.0
  mavenProjectName: @project.artifactId@
  mavenProjectVersion: @project.version@




一,Spring Boot的概念

spring boot是Pivotal团队提供的全新框架,
其设计目的是用来“简化”spring应用的创建、运行、调试、部署等

使用spring boot可以做到专注于spring应用的开发
而无需过多关注XML的配置。springboot使用“习惯优于配置"的理念来实现spring
应用开发的简化

使用springboot可以不用或者只需要很少的spring配置就可以让企业项目快速的运行起来

springMVC Spring Mybatis整合
springboot 可以简化各种框架的整合和配置,使基于spring应用的开变得更加简单和高效。

核心:
内嵌的servlet容器
简化的maven配置
自动配置spring
自动化配置框架的整合

二,开发第一个springboot应用

springboot应用是基于maven开发

1.在pom.xml文件中配置springboot的核心启动器

<!--spring-boot-starter-parent是Spring Boot的核心启动器,
	包含了自动配置、日志和YAML等大量默认的配置,大大简化了我们的开发。
	引入之后相关的starter引入就不需要添加version配置,
	spring boot会自动选择最合适的版本进行添加。
-->
  <parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.0.RELEASE</version>
	<relativePath/> 
  </parent>

只要导入了springboot的核心启动器,后续的依赖版本就需要自己指定了
因为springboot会自己选择合适的版本关联

2.加入一个web开发的启动器

 <!-- spring-boot-starter-web包含了Spring Boot预定义的一些Web开发的常用依赖包如: spring-webmvc,Tomcat.... -->
  	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

3.定义一个控制器Controller
SpringBoot的自动扫描是以启动类App.java为基准扫描与app类同级的所有包,以及所有的子包 。

三,spring的自动化配置

框架的整合以及配置文件的配置都是自动配置好的,无需程序员理会

spring.factories文件
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration相当于springmvc-servlet.xml文件

@Configuration ->xml文件
@Bean -><bean>

类相当于配置文件

功能详解:

一、spring boot 数据访问

​ WEB应用中,数据访问相当重要
​ spring boot数据访问方式:
​ Spring Data
​ Spring Data JPA
​ JdbcTemplate
​ Mybatis
​ 数据访问的进化:
​ JDBC > Mybatis(半自动化) > Hibernate(全自动化) > JPA > Spring Data

1.在spring boot中使用spring data JPA访问数据库
​ spring data JPA是属于spring data项目的

spring data是如何简化hibernate开发的?
  spring data项目提供了很多核心接口
  这些接口已经封装了对数据库操作的API
  我们项目的数据访问层接口只要继承这些核心接口
  就拥有了对数据库的CRUD访问操作。

spring data的核心接口:
  Repository
    /
    CrudRepository
      /
      PagingAndSortingRepository(多了分页和排序功能)
        /
	JpaRepository(spring data JPA)

	(1)开始使用CrudRepository操作数据库
	a.在pom.xml中加入springboot整合spring data的核心启动器

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

	b.因为要访问数据库,所以需要配置访问数据库的基本信息

	在全局配置文件中application.properties配置

	c.定义数据访问层接口,继承CrudRepository
	(2)PagingAndSortingRepository
	     分页  , 排序。

	(3)JpaRepository

	(4)简单的条件查询,根据接口的方法名称确定的

	(5)多表查询,关联查询
	Student     Clazz
	N              1
	使用@Query 写SQL语句
	DML  @Modifying
	@NameQuery
	(6)动态查询
	继承接口Specification

	public List<Map<String, Object>> getStusDynamic(Student student) {
	
	List<Student> stus=studentRepository.findAll(new Specification<Student>() {
		@Override
		public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query,
				CriteriaBuilder cb) {
			//封装动态条件
			//root->代表了Student表 select s from Student s
			//cb ->构建动态条件
			//本集合用于封装查询条件
			List<Predicate> predicates = new ArrayList<Predicate>();  
			
			if(student!=null){
				/** 是否传入了姓名来查询  */
				if(!StringUtils.isEmpty(student.getName())){
					//and s.name like  "%"+student.getName()+"%"
					predicates.add(cb.like(root.<String> get("name"),"%" + student.getName() + "%"));
				}
				/** 是否传入了地址来查询  */
				if(!StringUtils.isEmpty(student.getAddress())){
					predicates.add(cb.like(root.<String> get("address"),"%" + student.getAddress() + "%"));
				}
				/** 是否传入了性别来查询 */
				if(student.getSex() != '\0'){
						predicates.add(cb.equal(root.<String> get("sex"),student.getSex()));
					}
					/** 判断是否传入了班级信息来查询 */
					if(student.getClazz()!=null && !StringUtils.isEmpty(student.getClazz().getName())){
						//s.clazz
						root.join("clazz", JoinType.INNER);
						//s.clazz.name
						Path<String> clazzName = root.get("clazz").get("name");
						//s.clazz.name=student.getClazz().getName()
						predicates.add(cb.equal(clazzName, student.getClazz().getName()));
					}
				}
				return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();




​ }
​ });
​ //stus动态查询的
​ List<Map<String,Object>> studatas=new ArrayList<>();
​ if(stus!=null && stus.size()>0) {
​ stus.forEach(s -> {
​ Map<String,Object> data = new HashMap<>();
​ data.put("name", s.getName());
​ data.put("age", s.getAge());
​ data.put("sex", s.getSex());
​ data.put("address", s.getAddress());
​ data.put("clazzName", s.getClazz().getName());
​ studatas.add(data);
​ });
​ }
​ return studatas;
​ }

3.Spring Boot使用JdbcTemplate

4.Spring Boot整合Mybatiss

对于mybatis框架来说,需要告诉他数据访问层接口的位置:
---因为Mybatis框架要为数据访问层接口做实现类对象
以及持久化类的位置:
---因为要为实体类做别名

再主类中使用注解表明注解地址
//扫描数据访问层接口的包名
@MapperScan("crudrepository.repository")

使用技巧:

1.热部署

<!-- Spring Boot spring-boot-devtools 依赖 热部署插件 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<optional>true</optional>
		<scope>true</scope>
	</dependency>

<!-- 添加spring-boot-maven-plugin -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<!-- 如果没有该项配置,devtools不会起作用,即应用不会restart -->
					<fork>true</fork>
				</configuration>
			</plugin>
		</plugins>
	</build>

2.单元测试
引入依赖

<!-- spring-boot-starter-test 依赖.... -->
  	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

3.Spring Security

一个强大且高度可定制的身份验证和访问控制框架

安全框架主要包含两个框架:
	认证:确认用户可以访问当前系统
	授权:确定用户在当前系统中是否能够执行某个操作,即用户所拥有的功能权限

spring security包含多个模块:
	核心模块
	远程调用
	Web网页
	配置
	LDAP
	ACL访问控制表
	CAS
	OpenID
	Test

<!-- 添加spring-boot-starter-security 依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5