GrumpyRodriguez
GrumpyRodriguez

Reputation: 769

Can I define a Spring @bean as a @Repository or @Service?

I'm wiring a third party library into a Spring Boot application and I'd like to both control its lifecycle and benefit from exception transform/translation capability of @Repository.

I can inherit from the type in the third party library and use @Repository on the inherited type, but that would not work for final classes and I want the lifecycle flexibility of @bean.

Is there any way I can declare a bean to also act like a stereotype?

Upvotes: 0

Views: 371

Answers (1)

codependent
codependent

Reputation: 24452

As far as I know there's no way you can add stereotype information to an existing class. There's a workaround as seen in this SO answer, however it seems kind of complicated.

I'd suggest a more straightfoward approach: favor composition over inheritance. This way you can create your own class that wraps the third party library class functionality, annotate it as @Repository and define it as a ´@Bean´:

@Repository
public class LibWrapper {

    private TrirdPartyClass wrapped;

    public void insert() {
        wrappped.insert();
    }
}

@Configuration
public class LibWrapperConfiguration {

    @Bean
    public LibWrapper libWrapper(){
        return new LibWrapper();
    }
}

Upvotes: 1

Related Questions