gpt4 book ai didi

java - Spring Boot中使用YAML配置初始化Bean

转载 作者:行者123 更新时间:2023-11-30 06:19:31 25 4
gpt4 key购买 nike

我想在 Spring Boot 中初始化 bean 或服务时读取一些属性,例如数据库访问配置。

有人知道好的方法吗?

这是我当前的代码片段。

public class SampleApplication implements ApplicationRunner
{
@Autowired
private YAMLConfig myConfig;

@Override
public void run(ApplicationArguments args) throws Exception
{
System.out.println(myConfig != null); //YAMLConfig has been intialized here
}

public SampleApplication()
{
System.out.println(myConfig == null); //myConfig is null
}

@Configuration
public static class Config
{
@Bean
@ConditionalOnProperty(value = {"batch.execute"}, havingValue = "SampleApplication")
public SampleApplication sampleApplication()
{
return new SampleApplication();
}
}
}

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig
{
private String environment;

public String getEnvironment()
{
return environment;
}

public void setEnvironment(String environment)
{
this.environment = environment;
}
}

感谢您查看此内容!

最佳答案

在您的 SampleApplication 类中创建此方法

@PostConstruct
public void init() {
// at this point, all the dependency injection has happened already
myConfig.doStuff()
}

所有bean初始化完成后,spring会自动调用它。

关于java - Spring Boot中使用YAML配置初始化Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48478441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com