多模块组件扫描在Spring Boot中不起作用

问题描述:

我有两个模块的网络和业务.我已将业务包含在网络中.但是,当我尝试使用@autowired将企业的服务接口包含到Web中时,它给出的是org.springframework.beans.factory.NoSuchBeanDefinitionException.

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.

因此,基本上@SpringBootApplication不能从业务模块中扫描@Service.

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

这很简单,我想念吗?

如果我在@SpringBootApplication类中为该服务添加了@Bean,则它可以正常工作.

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

代码:

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);
    }
}

模块1中的类,正在从模块2中调用类:

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;
....
}

模块2:

package com.manish.service;

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

@Service
public class SampleServiceImpl implements SampleService {
}

谢谢

@SpringBootApplication仅扫描带有注释本身的类的包以及下面的所有包.

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

示例:如果带有SpringBootApplication批注的类在包com.project.web中,则将扫描此包以及所有下面的包.

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

但是,如果您的服务位于软件包com.project.business中,则不会扫描Bean.

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

在这种情况下,您必须将注释@ComponentScan()添加到您的应用程序类,然后将要扫描的所有软件包都添加为该注释中的值,例如@ComponentScan({"com.project.web", "com.project.business"}).

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"}).