springboot解析自定义yml文件
在Spring Boot中,你可以使用@ConfigurationProperties
注解来绑定自定义的YAML文件到一个配置类中。以下是一个简单的例子:
首先,定义一个配置类:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "custom")
public class CustomProperties {
private String propertyOne;
private int propertyTwo;
// standard getters and setters
public String getPropertyOne() {
return propertyOne;
}
public void setPropertyOne(String propertyOne) {
this.propertyOne = propertyOne;
}
public int getPropertyTwo() {
return propertyTwo;
}
public void setPropertyTwo(int propertyTwo) {
this.propertyTwo = propertyTwo;
}
}
然后,在application.yml
中添加你的自定义配置:
custom:
property-one: value1
property-two: 123
最后,在需要使用这些配置的地方注入CustomProperties
:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
private final CustomProperties customProperties;
@Autowired
public MyComponent(CustomProperties customProperties) {
this.customProperties = customProperties;
// 使用customProperties中的配置
}
}
确保你的Spring Boot应用程序主类上有@EnableConfigurationProperties(CustomProperties.class)
注解,如果你想要自动注册CustomProperties
。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(CustomProperties.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
这样,Spring Boot就会在启动时将custom
前缀的配置绑定到CustomProperties
类的实例中,你可以在应用程序的任何部分通过@Autowired
注入这个类并使用它的配置。
评论已关闭