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<T> {

    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<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<String> 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:总上传的数据最大大小

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353