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;
        }
    }
  • 相关阅读:
    php -- php数组相关函数
    php -- 数组排序
    php -- in_array函数
    php -- 魔术方法 之 删除属性:__unset()
    无符号整型与有符号整型相运算规则
    N个节点的二叉树有多少种形态
    getopt_long
    typedef
    约瑟夫环问题算法(M)
    C语言基础
  • 原文地址:https://www.cnblogs.com/jnba/p/10832801.html
Copyright © 2011-2022 走看看