栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 自定义参数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 自定义参数

1、生成自定义参数的对应文件,如下图,自建配置文件diy.yml放在项目的根目录下面的config文件夹下

编辑配置文件内容

2、新建配置类DiySetting.class

编辑内容

package com.joe.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileUrlResource;

import java.net.MalformedURLException;
import java.util.Objects;


@Configuration
public class DiySetting {
    @Bean
    public static PropertySourcesPlaceholderConfigurer loadYaml(){
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        //如果在classpath下则这样写yaml.setResources(new ClassPathResource("config/diy.yml"));
        try {
            yaml.setResources(new FileUrlResource("config/diy.yml"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }
}

3、增加实体类,绑定参数,此处引入了lombok插件简化代码

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


@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
    String name;
    int age;
    boolean male;
}

4、读取参数

package com.joe;

import com.joe.entity.Person;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@RequiredArgsConstructor(onConstructor_ = @Autowired)
@SpringBootApplication
public class Demo11Application implements CommandLineRunner {
    private final Person person;
    public static void main(String[] args) {
        SpringApplication.run(Demo11Application.class, args);

    }

    @Override
    public void run(String... args) {
        System.out.println(person.getName());
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/710015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号