I’m trying to use an object which is in an external library, but when I use the @Autowired property, it is not found by the application.
The main application has the following annotations:
@SpringBootApplication @ComponentScan(basePackages = {"com.XXXX.prj.business.modules"}) @EntityScan("com.XXXX.prj") @EnableJpaRepositories(basePackages = {"com.XXXX.prj.business.modules.repositories"})
In the com.XXXX.prj.business.modules I have a class that calls the object of the dependency, called MailService, in this way:
@Component public class MailNotificatorImpl implements Notificator { @Autowired private MailService mailService;
Here is the problem, this mailService object is not found as a bean type. The MailService is in an external library, called YYYY-commons. The class of the library has the interface and its implementation, and the implementation has this annotation:
@Service("mailService") public class MailServiceImpl extends GenericService implements MailService, Serializable {
I don’t know what I’m doing bad because in other application I use in the same way and it’s working.
Can you give me some help in this? Thanks a lot!
Advertisement
Answer
In your component scan, you are only scanning the defined package, and any sub-package from there. This meand that the third party lib is not caught in the component scan, hence the bean is not registered.
The options you have is to:
- use the
@ComponentScan
annotation on your main application class and add both your own base package, and the package of the third party lib.
@ComponentScan(basePackages = {"my.base.package", "third.party.package"}) public class MySpringBootApplication{}
- register the bean yourself by adding something like the below to e.g. your main application class:
@Bean public MailService mailServiceBean() { return new MailServiceImple(); }