static静态变量与非静态变量获取配置文件application中变量值的区别

static静态变量与非静态变量获取配置文件application中变量值的区别

在spring boot项目配置文件application.yml或者application.properties中添加两个变量并赋值

value: 127.0.0.1:8081
staticvalue: 127.0.0.1:8081

在controller文件中通过@value注解获取配置文件中变量值,并赋值于普通变量

package com.example.jpahappy.Controller;

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;

@RestController
@RequestMapping("/getvalue")
public class getvalue {

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

    @RequestMapping(method = RequestMethod.GET,value="/getvalue")
    public String getvalue(){
        return "this:"+value;
    }
}

在浏览器中调用getvalue方法,获得结果value值读取到配置文件中赋予变量值
在这里插入图片描述同样的方法,controller类中读取配置文件中变量,赋值于静态变量,静态变量与非静态变量赋值与获取方法相同

package com.example.jpahappy.Controller;

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;

@RestController
@RequestMapping("/getvalue")
public class getvalue {

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

    @Value("${staticvalue}")
    private static String staticvalue;

    @RequestMapping(method = RequestMethod.GET,value="/getvalue")
    public String getvalue(){
        return "this:"+value;
    }

    @RequestMapping(method = RequestMethod.GET,value="/getstaticvalue")
    public static String getstaticvalue(){
        return "this:"+staticvalue;
    }
}

浏览器中通过getstaticvalue方法却未能成功将配置文件中变量值赋值于静态变量,静态变量staticvalue值为null
在这里插入图片描述既然如此,对静态变量赋值进行如下修改

@RestController
@RequestMapping("/getvalue")
public class getvalue {

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

    private static String staticvalue;

    @Value("${staticvalue}")
    public void setStaticvalue(String staticvalue){
        this.staticvalue = staticvalue;
    }

    @RequestMapping(method = RequestMethod.GET,value="/getvalue")
    public String getvalue1(){
        return "this:"+value;
    }

    @RequestMapping(method = RequestMethod.GET,value="/getstaticvalue")
    public static String getvalue2(){
        return "this:"+staticvalue;
    }
}

先定义静态变量,通过setStaticvalue方法与@value注解成功实现将配置文件中变量赋值于静态变量
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未来悦,事享成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值