1

我有一个 spring-boot 应用程序(Java8,spring-boot 2.1.4-RELEASE)。

业务层中的一项服务需要从我的类路径中的某个 jar 中 @Autowire 一个 bean。为了实现这一点,我必须添加 @ComponentScan({"package.to.my.bean.inside.the.jar"}) 并且它被神奇地扫描并成功连接(这被添加到主 spring-boot 类中声明主要方法)。

但是,从那时起我的控制器没有被扫描,因此 DispatcherServlet 为我触发的每个请求(默认调度程序)返回 404。实际上,我的整个 spring-boot 应用程序注释都被忽略了——没有执行扫描。只是强调一下 - 在添加 @ComponentScan 之前,该应用程序运行良好。

主要的 spring-boot 应用程序类:

package com.liav.ezer;

// This is the problematic addition that cause the endpoints to stop
// inside a jar in the classpath, in com.internal.jar package resides an 
// object which i need to wire at run time
@ComponentScan({"com.internal.jar"})
@SpringBootApplication
public class JobsApplication {
    public static void main(String[] args) {
        SpringApplication.run(JobsApplication .class, args);
        }
}

控制器示例:

package com.liav.ezer.controller;

@RestController
@EnableAutoConfiguration
@RequestMapping(path = "/jobs")
public class JobController {

    @GetMapping(path="/create", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    String createJob(@RequestParam() String jobName) String jobName){       
        return "job created...";
    }
}

我尝试将我的 spring-boot 应用程序基础包添加到 @ComponentScan 中的包列表中,但没有成功。我尝试将包声明的范围缩小到仅在我需要但没有运气的类上。这是代码

4

2 回答 2

2

根据Spring 文档

配置组件扫描指令以与 @Configuration 类一起使用。提供与 Spring XML 元素并行的支持。可以指定 basePackageClasses() 或 basePackages()(或其别名 value())来定义要扫描的特定包。如果未定义特定的包,则会从声明此注解的类的包中进行扫描。

在您添加的情况下

@ComponentScan({"com.internal.jar"}) 您正在禁用扫描 com.liav.ezer.controller

要修复它,您可以执行以下配置

@ComponentScan(basePackages = {"com.internal.jar", "com.liav.ezer.controller"})

于 2019-05-31T19:36:27.723 回答
0

如果是这样,删除@ComponentScan,可以在自己的配置中声明该bean。试试下面

@SpringBootApplication
public class JobsApplication {
    public static void main(String[] args) {
        SpringApplication.run(JobsApplication .class, args);
        }
     @Bean
     public BeanInOtherJar xxBean(){
        return new com.internal.jar.XXX();
     }
}
于 2019-05-31T19:19:13.670 回答