Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi module component scanning not working in spring boot

I am having two module web and business. I have included business in the web. But when I try to include a service interface from business into web using @autowired, it is giving org.springframework.beans.factory.NoSuchBeanDefinitionException.

So, basically @SpringBootApplication is not able to scan the @Service from business module.

Is it something simple, I am missing?

If I add @Bean for that service in the @SpringBootApplication class, it is working fine.

Code:

package com.manish;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class SpringBootConfiguration {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootConfiguration.class, args);
    }
}

Class from module 1 from which is calling class from module 2:

package com.manish.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.co.smithnews.pmp.service.contract.UserRegistrationService;

@RestController
@RequestMapping("/testManish")
public class SampleController {

    @Autowired
    private SampleService sampleService;
....
}

Module 2:

package com.manish.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SampleServiceImpl implements SampleService {
}

Thanks,

like image 671
krmanish007 Avatar asked Oct 12 '15 11:10

krmanish007


1 Answers

@SpringBootApplication only scans the packages of the class with the annotation itself and all packages below.

Example: If the class with the SpringBootApplication annotation is in the package com.project.web, then this packages and all below that are scanned.

However, if you have your services in the package com.project.business, the beans won't be scanned.

In that case you have to add the annotation @ComponentScan() to your application class, and add all packages you want to scan as value in that annotation, e.g. @ComponentScan({"com.project.web", "com.project.business"}).

like image 65
dunni Avatar answered Nov 04 '22 12:11

dunni