0

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?

GrumpyRodriguez
  • 649
  • 5
  • 12

1 Answers1

1

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();
    }
}
codependent
  • 23,193
  • 31
  • 166
  • 308
  • Thanks, delegation is indeed something I had in mind but I was not sure how default lifecycle management for @ repository would interact with a different policy (scope) I'd set for @ Bean. I guess I can try and see. The answer you provided the link to looks complicated and I'm not sure I understand what is suggested there. – GrumpyRodriguez Nov 25 '19 at 13:09