程序员SpringBoot极简教程 · Spring Boot 我爱编程

Spring Boot:注解、异常、配置

2017-12-26  本文已影响428人  聪明的奇瑞

概述

配置

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]}

多环境配置

注解

@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();
    }
}
@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 加载了
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命名策略配置

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:总上传的数据最大大小

上一篇 下一篇

猜你喜欢

热点阅读