简体   繁体   中英

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?

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM