Java使用SpringBoot应用配置文件

*配置文件yml和properties均可,以下以yml为例
1.设置配置文件
app:
service:
name: justin
id: 000
2.创建配置文件映射类

@Component//如报错请将此注解注释,因为此时出现了该bean被注册两次的情况
@ConfigurationProperties("app.service")
public class ServiceProperties {

    private String name;//注意该字段名要与配置文件中保持一致
    private String id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

3.创建配置文件读取类并将值赋给对应服务

@Configuration
@EnableConfigurationProperties(ServiceProperties.class)
public class ServiceAutoConfiguration {

    @Autowired
    private ServiceProperties properties;

    @Bean
    public ServiceExecutor serviceExecutor(){
        return new ServiceExecutor(properties.getName(),properties.getId());
    }
}

4.创建并调用对应的服务类

public class ServiceExecutor {

    private final String serviceName;

    private final String serviceId;

    public ServiceExecutor(String serviceName, String serviceId) {
        this.serviceName = serviceName;
        this.serviceId = serviceId;
    }

    public void execute(){
        System.out.println("--模拟对参数进行了处理");
        System.out.println("serviceName:"+serviceName);
        System.out.println("serviceId:"+serviceId);
    }
}

@RestController
public class TestController {

    @Autowired
    private ServiceExecutor serviceExecutor;

    @RequestMapping("/test")
    public void test(){
        serviceExecutor.execute();
    }
}
@ConditionalOnProperty
/**
*该注解用于判断当前@Configuration是否有效
*使用方法:
*1.直接读取配置文件中的值:
**/
@ConditionalOnProperty(value="app.service.enabled")
/**
*2.//如果synchronize在配置文件中并且值为true
**/
@ConditionalOnProperty(name = "synchronize", havingValue = "true")
 
/**
*使用场景:
*在微服务开发中,一般会有一个服务用来存放公共的config配置,
*但是每个服务可能会有细微的区别,这时我们只需要将config服务中提供的引用false掉,重新写入自己的配置即可
**/

发表回复

您的电子邮箱地址不会被公开。

3 × 4 =