C96
C96

Reputation: 529

Autowire service to use inside bean

Is it possible to somehow autowire a service and use it inside another bean? I have this:

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
                  .route(r -> r.path("/api/wallet/slot/thunderkick/**") //intercept calls to
                                   .uri("http://mrq-wallet-forwarder.mircloud.host/") //forward to
                               .id("thunderkickModule"))
                  .build();
}

but I need that and this doesnt seem to be the right way to do it:

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder, 
                ***@Autowired val discoveryService: AccountDiscoveryService***) {
    return builder.routes()
                  .route(r -> r.path("/api/wallet/slot/thunderkick/**") //intercept calls to
                               .uri(discoveryService.getHost()) //forward to
                               .id("thunderkickModule"))
                  .build();
}

Any recommendations would be really helpful and appreciated. Thank you in advance

Upvotes: 0

Views: 139

Answers (1)

Dmytro Bill
Dmytro Bill

Reputation: 101

Of course you can do it. Try it like this:

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder, 
                      @Autowired AccountDiscoveryService discoveryService) {
    //Objects.requiredNotNull(discoveryService); //null check if discoveryService can be null
    return builder.routes()
                  .route(r -> r.path("/api/wallet/slot/thunderkick/**") //intercept calls 
                               .uri(discoveryService.getHost()) //forward to
                               .id("thunderkickModule"))
                  .build();
}

Also you can move String values to property file. It is better way for configuration classes.

Upvotes: 3

Related Questions