您的位置:首页 > 编程语言 > Java开发

springboot静态方法和非静态方法获取配置文件的参数

2020-04-27 19:31 3719 查看

背景:springBoot2.1版本
数据准备:
1.yml文件

name: xixihaha
pwd: 123456
url: http:baidu.com

2.创建一个对应的实体类YmlBean.java,生成set,get方法
细节说明:
1,类上加注解@Configuration;
2,在set方法上加@Value("${XXX}"),其中XXX与yml文件对应。有层级关系的话用.隔开;
3,set方法都是非静态的

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class YmlBean {
//静态变量
private static String name;
//非静态变量
private String pwd;

@Value("${name}")
public  void setName(String name) {
YmlBean.name = name;
}
@Value("${pwd}")
public void setPwd(String pwd) {
this.pwd = pwd;
}

public static String getName() {
return name;
}
public String getPwd() {
return pwd;
}

3.获取内容
细节说明:
1,在调用数据的类上加@Component注解
2,非静态方法获取参数更简单方法,如url,不用实体类get方法,在类中用@value注解,直接使用

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.example.demo.bean.YmlBean;
import com.example.demo.service.DoThingService;

@Component
public class DoThingServiceImpl implements DoThingService {

@Resource
private YmlBean ymlBean1;

private static YmlBean ymlBean;

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

@Override
public void getParam() {
aa();
String pwd = ymlBean1.getPwd();
System.out.println("非静态通过get方法获取pwd:"+pwd);
System.out.println("非静态直接获取url:"+ url);

}

public static void aa() {
String name=ymlBean.getName();
System.out.println("静态方法获取name:"+name);
}

}

结果如下:

静态方法获取namexixihaha
非静态通过get方法获取pwd:123456
非静态直接获取url:http:baidu.com
  • 点赞 1
  • 收藏
  • 分享
  • 文章举报
xiaopihai99 发布了1 篇原创文章 · 获赞 1 · 访问量 120 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: