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());
}
}



