Pooya
Pooya

Reputation: 4481

How can I define RestController manually in Spring?

I've a lot of RestController class that annotated with @RestController and works correctly. but in a situation I have to add one of them manually. I think I can define a bean in Spring configuration class, so I can define a RestService, but how?

For example :

@Configuration
public class Config ..... {

    ............

    @RestController
    public MyRestService myRestService() {
        if(shouldUseTypeA){
             return new MyRestService<TypeA>(myParams);
        }else{
             return new MyRestService<TypeB>(myParams);            
        }
    }
}

Upvotes: 2

Views: 2344

Answers (1)

Michal Foksa
Michal Foksa

Reputation: 12024

If shouldUseTypeA is something you know before the application starts, use it as a Spring profile and instantiate right controller according to the activated profile.

@Configuration
public class Config ..... {

    // Type A
    @Profile("shouldUseTypeA")
    @RestController
    public class TypeAService extends MyRestService<TypeA>(myParams){}

    // Otherwise type B
    @Profile("!shouldUseTypeA")
    @RestController
    public class TypeBService extends MyRestService<TypeB>(myParams){}
}

Upvotes: 3

Related Questions