Failing to import external jar containing bean

Viewed 402

I'm a little new t working with Spring so any help provided would be great.

I have a SpringApplication class (annotated with @SpringBootApplication. In another class (within the same project), it contains a ServiceClass class. When the class is in the same project, it runs as expected.

When the ServiceClass is moved to an external jar, I get the following error.

Description:

Field service in package-to-class.Comp required a bean of type 'package-to-class.ServiceClass' that could not be found.

The injection point has the following annotations:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'package-to-class.ServiceClass' in your configuration.

I am trying to find what I need to do to inject (@AutoWired) into my project with the above error.

2 Answers

By default, Spring Boot's component scanning only looks in the same package as the @SpringBootApplication and its descendants.

The approach I would suggest is using @Import to import specific beans from outside the project, or use @ComponentScan to import all beans from a package in another project.

@SpringBootApplication
@Import(ServiceClass.class)
public class SpringApplication {
    // ...
}

or

@SpringBootApplication
@ComponentScan(basePackages = "com.example.mylibrary")
public class SpringApplication {
    // ...
}

Okey some basic things, you have mixed up your packages a bit.

@SpringBootApplication will scan all classes in packages below the class this is annotated on. This annotation is an alias for @EnableAutoConfiguration, @Configuration and @ComponentScan means that @ComponentScan(basePackages = {"com.springdi.example"}, basePackageClasses = DependencyBasePackageClass.class) is not needed.

com.springdi.example     // class with @SpringBootApplication annotation
         |
         |
         |
com.springdi.example.*    // Will find all @Service, @Component, @Configuration
                          // in subpackages below the @SpringBootApplication 
                          // annotation

You can read more about the annotation here SpringBootApplication

Since your other annotated classes are NOT in the same package structure as the @SpringBootApplication you need to define all the places you want to scan for annotations.

@SpringBootApplication(scanBasePackages = {"com.springdi.example", "com.dependency.example"})

will probably include all the packages that you want to scan through.

Related