springboot的@Value注解使用

1、在application.yml定义属性

user:
  username: zhangsan
  age: 18
  sex: 男

2、一般获取配置文件的属性在service层

package com.xiaomin.wechat_brn.test;

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

@Service
public class UserService {

    @Value("${user.username}")
    private String username;
    @Value("${user.age}")
    private int age;
    @Value("${user.sex}")
    private String sex;


    public String getUserInfo(){
        return "姓名:"+username+"年龄:"+age+"性别:"+sex;
    }
}

3、Controller层使用

package com.xiaomin.wechat_brn.controller;

import com.xiaomin.wechat_brn.test.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    @Autowired
    private UserService userService;

    @RequestMapping("/hello")
    @ResponseBody
    public String fun(){
        String userInfo = userService.getUserInfo();
        return userInfo;
    }
}

4、测试


版权声明:本文为qq_38555490原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。