美文网首页SpringBoot
SpringBoot(二、配置文件注入,异常,测试,打包)

SpringBoot(二、配置文件注入,异常,测试,打包)

作者: 强某某 | 来源:发表于2019-05-13 16:17 被阅读0次

    配置文件自动注入

    配置文件

    如下,在application.yml中添加如下节点(也可以添加其他配置文件)

    zq:
      name: zqqq
      age: 30
    

    在controller中使用

    @RequestMapping("json")
    @RestController
    @PropertySource(value = "classpath:application.yml")
    public class JacksonController {
        @Value("${zq.name}")
        private String name;
       
        @GetMapping("/v2/json")
        public User getInfo() {
            User user=new User();
            user.setName(name);
            user.setSex("hahah");
            user.setTime(new Date());
            return user;
        }
    }
    

    配置文件注入bean中

    • 添加@Component
    • 添加注解@PropertySource(value = "classpath:application.yml")
    • @ConfigurationProperties(prefix = "zq") # 代表前缀

    对应实体类

    @Component
    @PropertySource("classpath:application.yml")
    @ConfigurationProperties(prefix = "zq")
    public class ServerConstant {
        //实验得出结论 此时@Value()不是必须的
        @Value("${name}")
        String name;
        @Value("${age}")
        int age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    }
    

    因为前缀zq既可以唯一确定属性值取配置文件中,但是如果不加(prefix = "zq")即省略前缀,则无法确定,此时需要添加 @Value();

    如果配置文件中没有前缀,只要属性名和配置文件中属性名一致,也可以省略@Value()

    控制器中使用

    @RequestMapping("json")
    @RestController
    public class JacksonController {
        @Autowired
        private ServerConstant serverConstant;
    
        @GetMapping("/v2/bean")
        public ServerConstant getHaha() {
            return serverConstant;
        }
    }
    

    单元测试

    基本测试

    1. 添加依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    1. 使用
    @RunWith(SpringRunner.class)  //底层juniSpringJUnit4ClassRunner
    @SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程
    public class SpringBootTests { }
    

    MockMvc讲解

    1、增加类注解

    @AutoConfigureMockMvc
    @SpringBootTest(classes={XdclassApplication.class})
    

    2、相关API

    perform:执行一个RequestBuilder请求
    
    andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
    
    andReturn:最后返回相应的MvcResult->Response
    

    个性化启动banner设置和debug日志

    1、启动获取更多信息 java -jar xxx.jar --debug

    2、修改启动的banner信息

    1)在类路径下增加一个banner.txt,里面是启动要输出的信息
    2)在applicatoin.properties增加banner文件的路径地址 spring.banner.location=banner.txt
    3)官网地址 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-banners
    

    异常相关

    配置全局异常

    @ControllerAdvice
    public class CustomExtHandle {
        /**
         * 全局异常
         * @param e
         * @param request
         * @return
         */
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        Object handleException(Exception e, HttpServletRequest request) {
            Map<String,Object> map=new HashMap<>();
            map.put("code",100);
            map.put("msg",e.getMessage());
            map.put("url",request.getRequestURL());
            return map;
        }
    }
    

    全局捕获异常,但是此时针对的是json返回的异常,例如路径找不到,返回的是页面数据时候,就不行了,可以再定义一个全局的返回页面的异常。利用ModelAndView

    自定义异常

    public class MyException extends RuntimeException {
    
        private String code;
        private String msg;
    
        public MyException(String code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }
    
    @ControllerAdvice
    public class CustomExtHandle {
        /**
         * 全局异常
         * @param e
         * @param request
         * @return
         */
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        Object handleException(Exception e, HttpServletRequest request) {
            Map<String,Object> map=new HashMap<>();
            map.put("code",100);
            map.put("msg",e.getMessage());
            map.put("url",request.getRequestURL());
            return map;
        }
    
    
        /**
         * 自定义异常: MyException集成的是RuntimeException
         * @param e
         * @param request
         * @return
         */
        @ExceptionHandler(value = MyException.class)
        @ResponseBody
        Object handleMyException(Exception e, HttpServletRequest request) {
            //addObject添加的数据,必须在模板引擎中获取,当前设置一个hmtl,暂时没有使用模板引擎
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error.html");
            modelAndView.addObject("msg", e.getMessage());
            return modelAndView;
            //同理,也可以返回json数据,同上一个方法
        }
    }
    

    如果是返回json数据 则用RestControllerAdvice,就可以不加@ResponseBody

    打War包

    • 添加依赖
    <build>
        <!-- 构建项目名称,请求的基本路径名称 -->
        <finalName>zqclass_springboot</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    

    此依赖不论jar(生成mainfast文件)还是war必须都有

    • 修改启动类
    @SpringBootApplication
    public class HelloApplication extends SpringBootServletInitializer {
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(HelloApplication.class);
        }
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(HelloApplication.class, args);
        }
    }
    
    图一.png

    访问测试: http://127.0.0.1:8080/zq_springboot/json/v2/bean

    相关文章

      网友评论

        本文标题:SpringBoot(二、配置文件注入,异常,测试,打包)

        本文链接:https://www.haomeiwen.com/subject/kgkraqtx.html