swagger-api/swagger-codegen

[JAVA] Support Javax injection for creation of API delegate instead of static factory pattern

Open

#3,930 opened on Oct 5, 2016

View on GitHub
 (16 comments) (1 reaction) (0 assignees)HTML (12,701 stars) (5,474 forks)batch import
Enhancement: FeatureGeneral: Suggestionhelp wanted

Description

Description

Replace/Complement static factory with DI injection

Currently, the generator for jersey and rest-easy use the static factory pattern to create the delegate that gets called by the REST API.

Swagger-codegen version

Whatever version this gradle plugin in using, (I think it's the current release).

Swagger declaration file content or url

Use the pet-store as an example.

Command line used for generation
swagger {
    inputSpec = "${project.projectDir.path}/spec/swagger.yaml"

    output = 'build/swagger'
    language = 'jaxrs-resteasy'

    additionalProperties = [
            'invokerPackage'   : 'edu.wpi.grip.web.swagger',
            'modelPackage'     : 'edu.wpi.grip.web.swagger.model',
            'apiPackage'       : 'edu.wpi.grip.web.swagger.api',
            'serializableModel': 'true'
    ]

    apis = ''
    models = ''
    supportingFiles = ''
}
Suggest a Fix

I'm using a custom api.mustache file that replaces the delegate creation with constructor injection.

import javax.inject.Inject;

public class {{classname}}  {
    private final {{classname}}Service delegate;

    @Inject
    {{classname}}({{classname}}Service delegate) {
        this.delegate = delegate;
    }

If a zero argument constructor is needed for other reasons and other frameworks both solutions could be implemented in parallel.

import javax.inject.Inject;

public class {{classname}}  {
    private final {{classname}}Service delegate;

    {{classname}}() { // Zero argument constructor because some frameworks need this
        this({{classname}}ServiceFactory.get{{classname}}(););
    }

    @Inject
    {{classname}}({{classname}}Service delegate) {
        this.delegate = delegate;
    }

Contributor guide