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;
        }
    }
  • 相关阅读:
    Kubernetes实战指南(三十三):都0202了,你还在手写k8s的yaml文件?
    Hadoop学习笔记
    Anaconda、Pycharm的安装与运行和Python环境的搭建
    常用编程软件文件配置(下载安装教程)
    error C2678: 二进制“<”: 没有找到接受“const _Ty”类型的左操作数的运算符
    Java 移位运算、符号位扩展
    c++ 集合操作
    c++ 输入与缓冲区
    python 装饰器
    python global 与 nonlocal
  • 原文地址:https://www.cnblogs.com/jnba/p/10832801.html
Copyright © 2011-2022 走看看