SpringBoot

Author Avatar
kevin
发表:2021-03-14 00:25:00
修改:2024-10-13 20:37:59

SpringBoot常用配置

1、配置文件加载位置
2、静态资源映射规则
3、templates文件夹
4、错误页面处理
5、WebMvcConfigurer配置

必须添加一个父工程,依赖boot

  <!--父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <dependencies>
        <!--web起步包
         注意:虽然是web工程,但不需要打war包,直接打jar就行
        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

建议不使用骨架,不用设置打包方式

创建类时,一定要有包名,不然springboot包扫描扫不到(默认会包扫描)

编写SpringBoot引导类

复合注解

@SpringBootApplication在哪个类上面,就以这个类为起点进行扫描

扫描当前包和子包

包含@ComponentScan,和@SpringBootConfiguration@EnableAutoConfiguration

//声明该类是一个SpringBoot引导类
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        // run方法 表示运行SpringBoot的引导类 run参数就是SpringBoot引导类的字节码对象
        SpringApplication.run(Application.class,args);
    }
}

简化配置

直接在resources下创建application.properties(yml) 直接配置自定义的属性即可

不懂 的可以查询

点击查询

简化部署

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

可以制作自定义启动器,或者简单打包部署

好处

spring自动整合ssm,(减少复杂的配置)约定大于配置

2.0和2.2以上.数据库从5.x升级到8.x,不向下兼容

连接数据库时,需要设置时区,还需要连接驱动时cj.

如果不满意自定义版本,可以设置

先查看默认版本号的key,在当前项目重写

<properties>
    <mysql.version>5.1.43 </mysql.version>
    </proprietary>

官方启动器,xxx.start表示一组依赖的集合描述

spring-boot-starter-*

集合描述

第三方启动器命名

*-spring-boot-starter

配置类

@configuration(proxyBeanMethods=true)
public class MyConfig{
    
    @bean
    public User getUser(){
        
        
    }
}

proxyBeanMethods=true 全量开发,每次获得的是同一个对象,单例,被容器代理

proxyBeanMethods=false 轻量开发,每次获得的不是同一个对象,不被spring代理

注解

@Import({xxx.class})
可以放在类上,可以自动创建这个类型的组件
默认名是全类名
条件注解
@Conditional
满足指定的条件,则进行组件注入
@ConditionalOnClass(xx.class)
有这个类就做某些事
@ConditionalOnMissClass
没有这个类就做某些事
@ConditionalOnBean
有这个bean做某些事
@ConditionalOnWebApplication
是一个web应用的时候做某些事
On后面是条件

导入spring的配置文件xml

@ImportResources("classpath:xxx.xml")放在配置类上非主程序

配置绑定(直译是配置属性)

以后可以直接通过实体类找配置属性

设置application.yml 文件

user:
  username: zhangsan
  password: 123
@Component   交给boot管理,否则无法使用配置绑定
@ConfigurationProperties(prefix=“配置文件中的key的前缀”)可以将配置文件中的配置自动与实体进行映射
@Component  (开启自动配置属性的时候,不需要这个注解)
@ConfigurationProperties(value = "user")
public class User implements Serializable{

    private String username;
    private String password;

    //生成 set get  tostring
}

其他地方直接注入user即可使用属性

开启属性配置功能,在配置类上写这个注解

适合第三方包,没有在类上注明@component的类,只能在配置类注入

//开启配置注解
@Configuration
@EnableConfigurationProperties(哪个类的属性配置)




@EnableConfigurationProperties(User.class)  自动把这个bean注入到容器中
user可以省去写component注解

自动配置原理

@SpringBootApplication主程序配置注解

是一个复合注解

包含@ComponentScan, 只是一个包扫描,从当前包和子包中扫描,默认把当前启动类所在的包作为扫描包的起点

@SpringBootConfiguration, 点进去就是一个@Configuration,表示当前类是一个配置类

@EnableAutoConfiguration 也是一个复合注解

里面重要的两个注解

@AutoConfigurationPackage
自动配置包,底层也是import,批量注册组件类(当前包下的所有组件)
@Import(AutoConfigurationImportSelector.class)
导入了 AutoConfigurationImportSelector 类组件
里面有个方法
getAutoConfigurationEntry(autoConfigurationMetadata,annotationMetadata);
容器批量导入一些组件
里面很重要的方法
getCandidateConfigurations(annotationMetadata, attributes);
要导入到容器中的配置类
通过在META-INF/spring.factories加载所有这个位置的文件
有的包有这个文件,有的包没有

热更新

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <!-- 这个需要为 true 热部署才有效 -->
    <optional>true</optional>
</dependency>
 <!--热部署配置-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

以后直接右键项目,build model即可

目录分析

原理,先去查找有没有对应的controller,才去找静态处理器

默认的静态资源路径

resources下的

static 专门放静态资源

templates专门放网页

建议使用静态资源前缀

yml文件里配置

spring
	mvc:
		static-path-pattern:/xxx/**

以后访问静态资源需加前缀

可能会对默认index不能访问,还有ico图标问题

yml配置文件

springboot支持二种类型的配置文件

  • properties属性配置文件
  • yaml配置文件
    • 适合做以数据中心配置文件

resources下,名字必须是application开头

kev: value 必须有一个空格隔开,不能使用tab

大小写敏感

缩进表示层级关系

缩进只能使用空格,几个无所谓

一般不需要写单双引号

手动开启rest风格

post表单需要method=post,隐藏域_method=put等

选择性开启,前后端分离,客户端有些可以直接发送异步rest请求

配置属性

spring:
	mvc:
		hiddenmethod:
			filter:
				enabled: true

整合Mybatis

使用spring_init初始化即可

application.yml 中添加数据量的连接信息

mybatis:
  type-aliases-package: com.kevin.domain # 指定mybatis别名包
  mapper-locations: classpath:com/kevin/dao/*.xml # 指定xml映射文件路径
logging:
  level:
    com.kevin.dao: debug # 配置日志
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8
    driver-class-name: com.mysql.jdbc.Driver
server:
  port: 18081

加密 yml 配置文件

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

yml文件写

jasypt:
  encryptor:
    password: 123456   盐值,随意

生成加密后的

  @Autowired
    private StringEncryptor stringEncryptor;
     String root = stringEncryptor.encrypt("root");
        String pwd = stringEncryptor.encrypt("root");

配置文件

spring:
  datasource:
    username: ENC(9ZbVZArwPSMrRnn3lZ68kQ==)
    password: ENC(pizCNDwDj3GSeUdseC2+ZA==)
    
    
    ENC()固定写法

整合Junit

<!--测试的起步依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
   不用写版本号
</dependency>

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperTest {
    
}

整合Spring Data JPA

  <!-- springBoot JPA的起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- MySQL连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
logging:
  level:
    com.kevin.dao: debug # 配置日志
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8
    driver-class-name: com.mysql.jdbc.Driver
  redis: #Redis
    port: 6379
    host: 127.0.0.1
  jpa:
    database: mysql
    show-sql: true
    generate-ddl: true
    hibernate:
      ddl-auto: update
      naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
server:
  port: 18081

实体配置实体

@Entity
@Table(name = "user")
public class User{
    @Id 这是主键id
    @GeneratedValue(strategy = GenerationType.IDENTITY)  主键id自增
    private Long id;
    private String username;
    private String password;
    private String name;
 
    //此处省略setter和getter方法... ...
}

mapper层

public interface UserDao extends JpaRepository<User,Integer> {
}
JpaRepository<User,Integer>  user表示实体类,Integer表示主键id类型

不用写sql语句

整合Redis

<!-- 配置使用redis启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置redis的连接信息

mybatis:
  type-aliases-package: com.kevin.domain # 指定mybatis别名包
  mapper-locations: classpath:com/kevin/dao/*.xml # 指定xml映射文件路径
logging:
  level:
    com.kevin.dao: debug # 配置日志
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8
    driver-class-name: com.mysql.jdbc.Driver
  redis: #Redis
    port: 6379
    host: 127.0.0.1
server:
  port: 18081

业务层注入

@Autowired            boot把jedis封装了
private RedisTemplate redisTemplate;
redisTemplate.boundValueOps(key).get();

扩展知识

配置类中只有一个有参构造器

所有参数的值都会从容器中寻找

评论