Spring Boot:注解、异常、配置

概述

  • Spring Boot它简化了配置,内嵌式tomcat容器,用于快速开发基于Spring的应用,是一个微框架

配置

  • 添加application.properties(可xml或yml)文件,除了配置数据库连接、日志等外,还可以添加属性,然后通过 @Value("${属性名}") 注解来加载对应的属性:
com.didispace.blog.name=程序猿DD
com.didispace.blog.title=Spring Boot教程
@Component
public class BlogProperties {

    @Value("${com.didispace.blog.name}")
    private String name;
    @Value("${com.didispace.blog.title}")
    private String title;

    // 省略getter和setter

}
  • 参数间也可以互相引用:
com.didispace.blog.name=程序猿DD
com.didispace.blog.title=Spring Boot教程
com.didispace.blog.desc=${com.didispace.blog.name}正在努力写《${com.didispace.blog.title}》
  • 也可以使用随机数:
# 随机字符串
com.didispace.blog.value=${random.value}
# 随机int
com.didispace.blog.number=${random.int}
# 随机long
com.didispace.blog.bignumber=${random.long}
# 10以内的随机数
com.didispace.blog.test1=${random.int(10)}
# 10-20的随机数
com.didispace.blog.test2=${random.int[10,20]}
  • 可以通过:java -jar xxx.jar -- server.port = 8888 设置端口,-- 后面就是对应配置文件中的值,可以通过 SpringApplication.sendAddCommandLineProperties(false) 屏蔽命令行访问属性

多环境配置

  • Spring Boot多环境配置文件名需要满足 application-{profile}.properties 格式,如:

    application-dev.properties:开发环境
    application-test.properties:测试环境
    application-prod.properties:生产环境

  • 然后在配置文件中通过 spring.profiles.active 属性设置生产环境,如:

    spring.profiles.active = test

注解

  • @SpringBootApplication:等于 @Configuration + @EnableAutoConfiguration + @ComponentScan
  • @RestController:是注解@Controller和@ResponseBody的结合,默认返回JSON
  • @Configuration:注解在类上,标记该类是一个配置类
  • @EnableAutoConfiguration:注解在配置类上、根据导入@EnableConfigServer的包自动配置 Spring Boot
  • @ComponentScan:注解在配置类上,扫描指定包下的所有类,将其注入IOC容器
  • @EntityScan:注解在入口类上,扫描指定包下的实体类
  • @ControllerAdvice:声明统一异常处理类
  • @ExceptionHandler:注解在方法上,声明对哪些异常进行处理
  • @Primary:注解在类上,当某个接口有多个实现类,通过 @Autowired 注入时,若不指定使用实现类,会优先使用该类进行注入
  • @EnableAutoConfiguration:注解在类上,让 spring boot 根据依赖项对 spring 进行自动配置,如添加了 spring-boot-starter-web 则配置 SpringMVC
  • @GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping:简化HTTP方法映射,更好的表达注解方法语义
  • @Import:可用于导入配置类,或普通 Java 类并将其声明为 Bean
  • @ConditionalOnProperty:该注解能够控制某个 configuration 是否生效,它得 name 属性用来从配置文件中读取某个值,如果该值为空,则返回 false,否则将与 havingValue 指定的值进行比较,一样则返回 true,否则 false,若返回 false,该 configuration 不生效
@Configuration
//如果synchronize在配置文件中并且值为true
@ConditionalOnProperty(name = "synchronize", havingValue = "true")
public class SecondDatasourceConfig {

    @Bean(name = "SecondDataSource")
    @Qualifier("SecondDataSource")
    @ConfigurationProperties(prefix = "spring.second.datasource")
    public DataSource jwcDataSource() {
        return DataSourceBuilder.create().build();
    }
}
  • @Order:控制配置类的加载顺序
@Configuration
@Order(2)
public class Demo1Config {
    @Bean
    public Demo1Service demo1Service(){
        System.out.println("demo1config 加载了");
        return new Demo1Service();
    }

}
@Configuration
@Order(1)
public class Demo2Config {

    @Bean
    public Demo2Service demo2Service(){
        System.out.println("demo2config 加载了");
        return new Demo2Service();
    }

}
输出结果:demo2config 加载了、demo1config 加载了
  • @ConfigurationProperties:可以将配置信息自动映射到实体类上,类似@Valid
connection.username=admin
connection.password=kyjufskifas2jsfs
connection.remoteAddress=192.168.1.1
@Component
@Data
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

    private String username;
    private String remoteAddress;
    private String password ;

}

异常处理返回JSON

  1. 创建返回的JSON对象:code(消息类型),message(消息内容),url(请求url),data(请求返回数据)
public class ErrorInfo {

    public static final Integer OK = 0;
    public static final Integer ERROR = 100;

    private Integer code;
    private String message;
    private String url;
    private T data;

    // 省略getter和setter

}
  1. 创建自定义异常类
public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
    
}
  1. 捕获异常进行处理
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo r = new ErrorInfo<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Some Data");
        r.setUrl(req.getRequestURL().toString());
        return r;
    }

}
@Controller
public class HelloController {

    @RequestMapping("/json")
    public String json() throws MyException {
        throw new MyException("发生错误2");
    }

}

Spring Boot配置:

spring.jpa.hibernate.naming.physical-strategy:Spring JPA命名策略配置

  • org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl(无修改命名)
  • org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy(驼峰命名)

spring.application.name:微服务应用程序名

server.context-path = /myspringboot:项目 contextPath 配置

server.error.path = /error:错误页配置

server.port = 9090:端口配置

server.session-timeout = 60:sesssion超时时间分钟

server.address = 192.168.16.11:绑定服务器IP,若启动时本机 IP 不一致抛异常

server.tomcat.max-threads = 800:tomcat最大线程数,默认200

server.tomcat.uri-encoding = UTF-8:tomcat的URI编码

server.tomcat.basedir = H:/springboot-tomcat-tmp:tomcat日志保存文件就

logging.path = H:/springboot-tomcat-tmp:日志文件目录

logging.file = myapp.log:日志文件名字

spring.datasource.url=jdbc:mysql://localhost:3306/testsql?useSSL=false:数据库url配置

spring.datasource.username=root:数据库用户名配置

spring.datasource.password=123456ly:数据库密码配置

spring.jpa.show-sql=true:显示sql语句进行调试

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect:SQL方言

spring.jpa.hibernate.ddl-auto=create:自动创建表、更新等

management.security.enabled=false:是否启用security

security.user.name:指定默认的用户名,默认为user

security.user.password:默认的用户密码

security.user.role:默认用户的授权角色

security.basic.enabled:是否看起鉴权,默认 true

spring.http.multipart.maxFileSize:单个文件最大大小

spring.http.multipart.maxRequestSize:总上传的数据最大大小

你可能感兴趣的:(Spring Boot:注解、异常、配置)