0
@Singleton
public class TestFunction extends FunctionInitializer {
    Logger log = LoggerFactory.getLogger(TestFunction.class);

    public TestFunction() {
    }

    public String execute() {
        return "Hello";
    }

}

我想以编程方式覆盖 application.yml 文件中的数据源属性,但不使用 bean 创建的事件侦听器。有没有办法做到这一点。就像使用属性创建自定义应用程序上下文一样。

我已将以下方法用于 Micronaut API 网关代理。

public class StreamLambdaHandler implements RequestStreamHandler {
.......
public StreamLambdaHandler() {
        try {
            log.info("Initializing Lambda Container");
            this.dbCredentialService = new DBCredentialService();
            // Get updated database credential map
            Map<String, Object> props = this.dbCredentialService.getDbCredential();
            // Create application context builder with updated properties
            // i.e Override datasources properties in application.yml
            builder = ApplicationContext.build().properties(props);
            handler = new MicronautLambdaContainerHandler(builder);
      }....
    ........
}

我们可以用 FunctionInitializer 做类似的事情吗?

4

1 回答 1

1

如果您计划仅覆盖数据源凭据属性,则可以通过这种方式完成。

@Factory
public class HikariDataSourceFactory {

    @Bean
    @Primary
    public DataSource dataSource(DBCredentialService credentialService) throws URISyntaxException {

        Map<String, Object> credentials = this.dbCredentialService.getDbCredential();
        String username = "user";
        String password = credentials.get("username");  
        
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres");
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName("org.postgresql.Driver");

        return new HikariUrlDataSource(config);
    }
}
于 2020-08-05T08:24:40.323 回答