How can I @Autowire a spring bean that was created from an external jar?

前端 未结 4 1632
情话喂你
情话喂你 2020-12-02 18:21

I have a module/jar that I\'ve created and am using as a util library. I created a service in there like so:

@Service
public class          


        
相关标签:
4条回答
  • 2020-12-02 18:35

    Ok - i had exactly the same problem - i wanted to autowire a mongo db repository interface from an external jar.

    • I could autowire every bean from that jar with using

      @SpringBootApplication(scanBasePackages = {"com.myrootpackage"})

    • However - autowiring the interface always failed with "Could not find blablabla..."

    But the interface was in the same package as the beans i could import. It turned out that searching for the mongo db interfaces is NOT taking the scanBasePackages from the @SpringBootApplication into consideration!

    It has to be explicitly configured via

    @EnableMongoRepositories(basePackages = {"com.myrootpackage"})
    

    Or you could move the main class "up" so the default searching works also for the mongo interfaces. So i understood the problem and found a solution. But i am still a bit unhappy because i need to configure the same lookup path twice. I find it stupid honestly.

    0 讨论(0)
  • 2020-12-02 18:36

    You can import application-context.xml for com.inin.architect.permissions in the following manner inside your main application.

    <import resource="classpath:/permissionApplicationContext.xml" />
    

    This will enable you to autowire beans from com.inin.architect.permissions that you have defined.

    0 讨论(0)
  • 2020-12-02 18:41

    You have to scan at least the package containing the class you want to inject. For example, with Spring 4 annotation:

    @Configuration
    @ComponentScan("com.package.where.my.class.is")
    class Config {
    ...
    }
    

    It is the same principle for XML configuration.

    0 讨论(0)
  • 2020-12-02 18:56

    Just a note on this, but you could decouple your dependency from spring. In your @Configuration class create

    @Bean public PermissionsService  permissionsService(){
       return new PermissionsService()
    }
    

    This will also allow it to be injected. Not that you have to remove your spring annotation, just an option making it potentially usable outside of spring.

    0 讨论(0)
提交回复
热议问题