以编程方式设置属性

问题描述 投票:0回答:1

在我的 micronaut 微服务中,我尝试以编程方式设置属性,而不是将其添加到 application.yml 中。我在下面提供了我的代码,还有我收到的错误。如何解决此问题,或者是否有其他方法可以实现此目的?

代码:

import io.micronaut.context.env.ActiveEnvironment;
import io.micronaut.context.env.PropertySource;
import io.micronaut.context.env.PropertySourceLoader;
import io.micronaut.context.event.ApplicationEventListener;
import io.micronaut.core.io.ResourceLoader;
import jakarta.inject.Singleton;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Singleton
public class CustomConfigSource implements PropertySourceLoader {

    @Override
    public Optional<PropertySource> load(String resourceName, ResourceLoader resourceLoader) {
        
        Map<String, Object> properties = new HashMap<>();
        properties.put("this.is.property.name", "value");
        return Optional.of(PropertySource.of("custom", properties));
    }

    @Override
    public Optional<PropertySource> loadEnv(String resourceName, ResourceLoader resourceLoader, ActiveEnvironment activeEnvironment) {
        return Optional.empty();
    }

    @Override
    public Map<String, Object> read(String name, InputStream input) throws IOException {
        return null;
    }
}

访问:

@Property(name = "this.is.property.name")
private String myProperty;

错误:

io.micronaut.http.server.RouteExecutor: Unexpected error occurred: Failed to inject value for field [myProperty]

我尝试添加日志,并且我看到

CustomConfigSource
内部的方法,例如
load
loadEnv
没有被调用。

java properties configuration yaml micronaut
1个回答
0
投票

有一种方法可以实现这一目标

public class CustomContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();

        Map<String, Object> myProperties = new HashMap<>();
        myProperties.put("this.is.property.name", "value");
        environment.getPropertySources().addFirst(
                new MapPropertySource("custom", myProperties));
    }
}

在启动时注册它

    new SpringApplicationBuilder(StarterMain.class)
            .initializers(new CustomContextInitializer())
            .run(args);

使用你的财产

@Value("${this.is.property.name}")
private String myProperty;
© www.soinside.com 2019 - 2024. All rights reserved.