zoukankan      html  css  js  c++  java
  • SpringBoot总结之属性配置

    一、SpringBoot简介

    SpringBoot是spring团队提供的全新框架,主要目的是抛弃传统Spring应用繁琐的配置,该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。从本质上说springboot不是一门新技术,主要是作用就是简化spring开发。

    (在Eclipse里使用SpringBoot,需要安装STS插件)

    二、SpringBoot属性配置

    SpringBoot项目,可通过application.properties配置文件,来配置项目相关信息。

    application.properties项目配置文件,打开是空白 里面可以配置项目,所以配置项目我们 alt+/ 都能提示出来。也可以使用yml文件做为项目配置文件。

    1)项目内置属性

    application.properties:

    server.port=8080
    server.servlet.context-path=/springTest

    application.yml:

    server:
      port: 8080
      servlet:
        context-path: /springTest

    2)自定义属性

    application.properties:

    server.port=8080
    server.servlet.context-path=/springTest
    hello=hello springboot

    application.yml:

    server:
      port: 8080
      servlet:
        context-path: /springTest
    hello: hello springboot
    /**
     * 获取自定义属性只要在字段上加上@Value("${配置文件中的key}"),就可以获取值
     * @author rdb
     *
     */
    @Controller
    public class UserController {
     
        @Value("${hello}")
        private String hello;
         
        @RequestMapping("/user")
        @ResponseBody
        public String test() {
            return hello;
        }
    }

    3)ConfigurationProperties  配置

    配置一个类别下的多个属性,我们可以@ConfigurationProperties配置到bean里,使用是直接注入就行了

    server:
      port: 8080
      servlet:
        context-path: /springTest
    hello: hello springboot
    test:
      ip: 192.168.11.11
      port: 90
    @Component
    @ConfigurationProperties(prefix="test")
    public class ConfigBean {
     
        private String ip ;
        private String port;
        public String getIp() {
            return ip;
        }
        public void setIp(String ip) {
            this.ip = ip;
        }
        public String getPort() {
            return port;
        }
        public void setPort(String port) {
            this.port = port;
        }
         
    }
    @Controller
    public class UserController {
     
        //获取自定义属性只要在字段上加上@Value("${配置文件中的key}"),就可以获取值
        @Value("${hello}")
        private String hello;
         
        //@ConfigurationProperties 配置的属性可以直接注入获取
        @Autowired
        private ConfigBean configBean;
         
        @RequestMapping("/user")
        @ResponseBody
        public String test() {
            System.out.println(configBean.getIp());
            System.out.println(configBean.getPort());
            return hello;
        }
    }
  • 相关阅读:
    BestCoder6 1002 Goffi and Squary Partition(hdu 4982) 解题报告
    codeforces 31C Schedule 解题报告
    codeforces 462C Appleman and Toastman 解题报告
    codeforces 460C. Present 解题报告
    BestCoder3 1002 BestCoder Sequence(hdu 4908) 解题报告
    BestCoder3 1001 Task schedule(hdu 4907) 解题报告
    poj 1195 Mobile phones 解题报告
    二维树状数组 探索进行中
    codeforces 460B Little Dima and Equation 解题报告
    通过Sql语句控制SQLite数据库增删改查
  • 原文地址:https://www.cnblogs.com/jnba/p/10832801.html
Copyright © 2011-2022 走看看