导入模块中的Spring引导和控制器

时间:2015-10-20 22:51:58

标签: java spring spring-mvc controllers

我有一个Spring启动应用程序,我想导入一个用spring boot编写的依赖项,它定义了一些控制器。

也许它很简单,但是如何让主应用程序能够在导入的模块中初始化所有这些控制器?当我尝试访问这些控制器的路径时,我得到一个错误,错过了给定路径的处理程序方法。我尝试如下:

@SpringBootApplication
@ComponentScan(basePackages = {"com.main.project", "com.imported.dependency"})
public class MyApplication
    implements CommandLineRunner {

    public static void main(final String... args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setWebEnvironment(true);
        app.run(args);

    }
}

即。我尝试了@ComponentScan,但没有任何反应。

我还试图查看控制器是否已加载:

ApplicationContext ctx = SpringApplication.run(FrontendApplication.class, args);

System.out.println("Let's inspect the beans provided by Spring Boot:");

String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
    System.out.println(beanName);
}

他们不是。我尝试删除@SpringBootApplication并使用@EnableAutoConfiguration@ComponentScan,但这不起作用。

建议?

4 个答案:

答案 0 :(得分:2)

@SpringBootApplication将自动扫描类路径中每个jar的具有子包命名空间的每个类。鉴于您的项目遵循Spring推荐的目录结构,所以您只需要该注释。请参阅:Spring Boot's Documentation on Structuring your code

尝试以下方法:

  1. 删除此行代码:

    @ComponentScan(basePackages = {"com.main.project", "com.imported.dependency"})
    
  2. 移动MyApplication,使其位于根目录中。根目录应遵循此命名约定com.example.project。因此,Spring引导应用程序主类的完全限定路径为:com.example.project.MyApplication,同时将exampleproject替换为您的公司主机名和项目名称。

  3. 将您的控制器放在其中的子包中(即使打包在单独的jar中)。所以他们的命名空间应该是这样的:com.example.project.controllers.

  4. 另外,不要忘记将@Controller@RestController注释添加到控制器类中。

  5. 希望这有帮助!

答案 1 :(得分:1)

在讨论主线程后,我试图设置一个类似你的小项目,我把它放在github上,我看不出任何问题。

看看https://github.com/e-ivaldi/mat_boy_test

这是来自日志 2015-10-24 17:22:02.900 INFO 31901 --- [main] swsmmaRequestMappingHandlerMapping:将“{[/ **]}”映射到公共java.lang.String com.somethingelse.controllers.SimpleController.xxx()< / p>

答案 2 :(得分:0)

也许您之间存在冲突:

@SpringBootApplication和@ComponentScan。

在Spring Boot文档中,我们可以阅读

  

@SpringBootApplication注释相当于使用@Configuration,@ EnableAutoConfiguration和@ComponentScan及其默认属性

链接:@SpringBootApplication documentation

您可以删除@SpringBootApplication并将其替换为@Configuration和@EnableAutoConfiguration吗?

答案 3 :(得分:0)

使用@Configuration和@EnableAutoConfiguration注释。