Spring Boot Service为空

时间:2016-11-03 05:49:08

标签: java spring spring-boot null

我目前正在使用Spring Boot,创建​​一个CommandLineRunner。一切正常,直到我尝试@Autowired我的类:它们总是为空并从Spring得到同样的错误:“创建名为'initBatch'的bean时出错:注入自动连接的依赖项失败: 没有找到类型[Utils]的限定bean用于依赖:预期至少有一个bean符合此依赖关系的autowire候选者。依赖注释。我仍然无法弄清楚为什么会发生这种错误。 这是我的代码:

@SpringBootApplication
public class InitBatch implements CommandLineRunner {

@Autowired
private Utils Utils;

@Override
public void run(String... args) throws Exception {
    System.out.println("Hello World");          
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(InitBatch.class, args);
}


@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();

       messageSource.setBasename("instances");
    return messageSource;
}

这是导致问题的Utils类:

@Configurable
@Service
public class Utils { 

private static final Logger LOG = LoggerFactory.getLogger(Utils.class);

     //NUMEROUS METHODS...
 }

此外,我还有另一个将de app加载为WS的Init。在服务器上运行所有内容,相同的类工作得很好。这是另一个正在运行的Init:

@Configuration
@ComponentScan({ "ws.controller","ws.service",
"ws.dao", "ws.util", "ws.filtro",
"ws.repository", "ws.model.log", "ws.logger.impl"})
@EnableAutoConfiguration
public class Init extends SpringBootServletInitializer { 

private static final int SECS = 10;

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Init.class);
}

/**
 * Main method.
 *
 * @param args String[].
 * @throws Exception Exception.
 */
public static void main(String[] args) throws Exception {
    SpringApplication.run(Init.class, args);
}


@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();

    messageSource.setBasename("instances");
    messageSource.setCacheSeconds(SECS);
    return messageSource;
}
}

我只是不明白为什么使用相同配置的相同文件可以与Init.java(作为tomcat web应用程序)一起使用,但是所有相同的文件都使用CommandLineRunner为空。

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

需要在ComponentScan处指定InitBatch注释(在不同包中为Utils类),以便在运行时扫描bean。

@Configuration
@ComponentScan("ws.util")
@EnableAutoConfiguration
public class InitBatch implements CommandLineRunner {
...
}

@SpringBootApplication文档 -

  

许多Spring Boot开发人员总是对其主类进行注释   使用@Configuration,@ EnableAutoConfiguration和@ComponentScan。   由于这些注释经常被一起使用(特别是如果   你遵循上面的最佳实践),Spring Boot提供了一个   方便的@SpringBootApplication替代方案。

相关问题