SpringBoot自定义并读取配置文件

第一步:新建配置文件实体类
package com.newcapec.swaggerdemo.configuration;

import lombok.Data;

@Data
public class MyConfig {
    private String username;
    private String password;
    private Integer age;
}
第二步:新建配置文件类
package com.newcapec.swaggerdemo.configuration;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
@Component
public class MyConfiguration {
    @Bean
    @ConfigurationProperties(prefix = "pss")
    public MyConfig myConfig(){
        return new MyConfig();
    }
}
第三步:编写配置文件
server:
  port: 8077

pss:
  username: pss
  password: 123456
  age: 25
第四步:使用
package com.newcapec.swaggerdemo.controller;
import java.util.ArrayList;
import	java.util.List;

import com.newcapec.swaggerdemo.configuration.MyConfig;
import com.newcapec.swaggerdemo.model.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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;

/**
 * hello
 * 作者: 彭赛赛
 * 创建时间:2019/12/26 13:59
 */
@RestController
@Api(tags = "测试模块")
public class Hello {

    @Autowired
    private MyConfig myConfig;

    @ApiOperation(value = "我是hello方法的value",notes ="我是hello方法的notes",response = String.class)
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        System.out.println(myConfig.getUsername() + ":" + myConfig.getPassword() + ":" + myConfig.getAge());
        return "hello";
    }
    
}
读取的结果展示:
pss:123456:25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值