如何在Dropwizard中向rest资源添加请求范围

时间:2016-09-30 12:21:41

标签: java spring rest dropwizard

我正在使用Dropwizard和Spring开发Restful应用程序。

我已启动并注册了spring上下文以及应用程序运行状况检查和休息资源,如下所示

Dropwizard配置类

public class DropwizardSpringApplication extends Application<DropwizardSpringConfiguration> {

    public static void main(String[] args) throws Exception {
        new DropwizardSpringApplication().run(args);
    }

    @Override
    public void initialize(Bootstrap<DropwizardSpringConfiguration> bootstrap) {
        // nothing to do yet
    }

    @Override
    public void run(DropwizardSpringConfiguration configuration,
            Environment environment) {

        // Init Spring context before we init the app context, we have to create a parent context with all the
        // config objects others rely on to get initialized
        AnnotationConfigWebApplicationContext parent = new AnnotationConfigWebApplicationContext();
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();

        parent.refresh();
        parent.getBeanFactory().registerSingleton("configuration", configuration);
        parent.registerShutdownHook();
        parent.start();

        //the real main app context has a link to the parent context
        appContext.setParent(parent);
        appContext.register(SpringConfiguration.class);
        appContext.refresh();
        appContext.registerShutdownHook();
        appContext.start();

        //Spring is started, getting all the beans that needed in DropWizard

        //health checks
        Map<String, HealthCheck> healthChecks = appContext.getBeansOfType(HealthCheck.class);
        for(Map.Entry<String,HealthCheck> entry : healthChecks.entrySet()) {
            environment.healthChecks().register(entry.getKey(), entry.getValue());
        }

        //resources
        Map<String, Object> resources = appContext.getBeansWithAnnotation(Path.class);
        for(Map.Entry<String,Object> entry : resources.entrySet()) {
            environment.jersey().register(entry.getValue());
        }

        //Link Spring to the embedded Jetty in Dropwizard
        environment.servlets().addServletListeners(new SpringContextLoaderListener(appContext));
    }
}

RestService

@Component
@Path("/hello")
//@Scope(value = "request")
public class RestService{

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/")
    public Response getResponse(Request request){
        //some codes here
        return response;
    }
}

如何将请求或会话范围添加到RestService。

0 个答案:

没有答案