springboot 自定义参数

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

springboot 自定义参数_第1张图片

编辑配置文件内容

springboot 自定义参数_第2张图片

2、新建配置类DiySetting.class

springboot 自定义参数_第3张图片

编辑内容

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;

/**
 * @author Joe
 * @version 1.0.0
 * @ClassName DiySetting.java
 * @Description TODO
 * @createTime 2022年01月18日 15:49:00
 */
@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;

/**
 * @author Joe
 * @version 1.0.0
 * @ClassName Method.java
 * @Description TODO
 * @createTime 2022年01月18日 09:38:00
 */
@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;

/**
 * @author Joe
 */
@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());
    }
}

你可能感兴趣的:(spring,boot,java,spring)