zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java项目属性的配置解决方案

2023-09-27 14:19:48 时间
  • application.properties文件可以方便地帮助细粒度地调整Spring Boot的自动配置
  • 不需要告诉Spring Boot为你加载此文件,只要它存在就会被加载,Spring和应用程序代码就能获取其中的属性
  • 不需要声明配置文件中值的类型,需要注入时再定义变量的类型即可

1 修改嵌入式Tomcat监听端口及访问前缀

这里写图片描述
点击运行,修改成功
这里写图片描述

2. yml VS properties

这里写图片描述
修改成功
这里写图片描述
运行结果
这里写图片描述

3. 动态注入外部属性文件中的值

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Shusheng Shi on 2017/5/3.
 */
@RestController
public class HelloController {

    @Value("${cupSize}")
    /*属性定义在外部属性文件(application.yml),使用占位符将其插入到bean中,Spring装配中,占位符形式为使用${...}包装的属性名称,
    若又依赖于组件扫描和自动装配来创建和初始化应用组件,就使用@Value,使用方法与@Autowired非常相似
    此时属性文件中cupSize的值就被注入到下面ccupSize变量中了*/
    private String cupSize;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return cupSize;
    }
}

4 在配置中再引用配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Shusheng Shi on 2017/5/3.
 */
@RestController
public class HelloController {

    @Value("${content}")
    private String content;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return content;
    }
}

5 更简易的配置

这里写图片描述

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Created by Shusheng Shi on 2017/5/3.
 */
@Component
/*表明该类作为组件类,并告知Spring要为此类创建bean,无需再显示配置该bean,Spring会做好一切*/
@ConfigurationProperties(prefix = "girl")
/*prefix:用来选择哪个属性的前缀名字来绑定
此示例为将girl前缀下的属性映射进来*/

//当配置文件属性较多时,将配置文件属性写到一个类中,需要属性值可以随意,而不需使用@Value一个一个累到死地注入
public class GirlProperties {
    private String cupSize;
    private Integer age;

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

相应的控制器类改为

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Shusheng Shi on 2017/5/3.
 */
@RestController
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return girlProperties.getCupSize();
    }

}

运行结果

6 应用多种配置环境

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述