Search code examples
springspring-boot

Make a third party class a service


I'm a beginner at Spring and beginning to understand how beans work. I want to declare a 3rd party class as a Service or a Bean. How do I do this? Should I just extend the class and annotate that?

example:

@Service
public class MyService { public MyService(ThirdPartyClass thirdPartyClass){..}....}

Here I cannot annotate ThirdPartyClass as a Service or otherwise


Solution

  • If your aren't the owner of the class that you would like to use as a bean, you can create the bean declaration in one of application's configuration classes:

    @Configuration
    public class YourConfig {
    
        @Bean
        public ThirdPartyClass thirdPartyClass() {
            return new ThirdPartyClass();
        }
    
    }
    

    Spring will instantiate an appropriate object based on that description and expose it via container to other beans.