@value注解和@ConfigurationProperties注解的基本使用

@value注解和@ConfigurationProperties注解的基本使用

基于@value读取默认配置

yml文件内容如下(装了STS插件以后即可直接使用,改后缀就行了)

user:
  username: xiongda
  sex: man
  age: 20
school:
  name: xtu
  location: hunan

备注:一定要注意之间要留空格,发现颜色变绿色了才是正确的格式,这个坑我刚踩

package com.example.demo.service.impl;

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

import com.example.demo.service.ReadConfigService;

@Service
public class ReadConfigServiceImpl implements ReadConfigService {
    
    @Value(value="${user.username}")
    private String username;
    
    @Value(value="${user.sex}")
    private String sex;
    
    @Value(value="${user.age}")
    private String age;
    
    @Value(value="${school.name}")
    private String name;
    
    @Value(value="${school.location}")
    private String location;
    
    @Override
    public String getUserMessage() {
        return "user ="+username+" sex ="+sex+" age="+age;
    }

    @Override
    public String getAuthorMessage() {
        return "schoolname="+name+"location="+location;
    }
    
}

基于@ConfigurationProperties读取默认配置

package com.example.demo.config;

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

@Component
@ConfigurationProperties(prefix="user")
public class HelloConfig {
    private String username;
    
    private String sex;
    
    private String age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

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

调用的controller层

package com.example.demo.web;

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

import com.example.demo.config.HelloConfig;
import com.example.demo.service.ReadConfigService;

@RestController
@RequestMapping("hello")
public class HelloController {
    
    @Autowired
    ReadConfigService readConfigService;
    
    @Autowired
    HelloConfig helloConfig;
    
    @RequestMapping("/user")
    public String say() {
       return "username "+helloConfig.getUsername()+" sex "+helloConfig.getSex()+" age "+helloConfig.getAge();
    }
    
    @RequestMapping("/school")
    public String school() {
       return readConfigService.getAuthorMessage();
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值