Proper Use Pattern for Services

classic Classic list List threaded Threaded
1 message Options
Tom
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Proper Use Pattern for Services

Tom
Brand new to Ratpack and trying to put together a simple Spring Boot + Ratpack application. I'm able to run the application fine and pass between handlers, but I'm not finding anything in the documentation or anywhere else about the proper way to reference ratpack services from the handler classes. Right now I'm just trying to autowire them, but not sure that this would be the preferred method.

Here's my application class:

@SpringBootApplication
@EnableRatpack
public class MyApplication {

    @Bean
    public Action<Chain> home() throws Exception {
        RatpackServer server = RatpackServer.of(s -> s
                        .serverConfig(ServerConfig.embedded())
                        .handlers(chain -> chain.all(ctx -> ctx.insert(new AdHocHandler()))
                        )
        );
        server.start();
        return chain -> chain.get(ctx -> ctx.insert(new AdHocHandler()));
    }

    public static void main(String... args) throws Exception {
        SpringApplication.run(MyApplication.class, args);
    }

}

Here's the handler class:

@Controller
public class AdHocHandler implements Handler {
    @Autowired
    private MyService myService;
   
    public void handle(Context context) throws Exception {
        myService.sayHello();
        context.next();
    }

    public MyService getMyService() {
        return myService;
    }

    public void setMyService(MyService myService) {
        this.myService = myService;
    }
}

and the service implementation:

@Component
public class MyServiceImpl implements ratpack.service.Service {
    public void onStart(StartEvent event) {
        System.out.println("Service registered.");
    }
   
    public void sayHello() {
        System.out.println("Hello!");
    }
}

I see the "Service registered" message in the console output when the ratpack server starts so assumed that spring is effectively linking components to the ratpack registry, but when we enter the handler class debugging the myService object is null so it would seem that the autowire is failing.

Is this an appropriate way to reference/call "ratpack services" or am I way off here?

Thanks!
Loading...