【发布时间】:2015-06-30 17:31:08
【问题描述】:
我正在尝试对 Spring Boot 应用程序中的 Service 类使用 @Autowired 注释,但它不断抛出 No qualifying bean of type 异常。但是,如果我将服务类更改为 bean,那么它可以正常工作。这是我的代码:
package com.mypkg.domain;
@Service
public class GlobalPropertiesLoader {
@Autowired
private SampleService sampleService;
}
package com.mypkg.service;
@Service
public class SampleService{
}
这是我的 SpringBoot 类:
package com.mypkg;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableTransactionManagement
public class TrackingService {
private static final Logger LOGGER = LoggerFactory.getLogger(TrackingService.class);
static AnnotationConfigApplicationContext context;
public static void main(String[] args) throws Exception {
SpringApplication.run(TrackingService.class, args);
context = new AnnotationConfigApplicationContext();
context.refresh();
context.close();
}
}
当我尝试运行它时,我得到以下异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mypkg.service.SampleService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
但是当我从 SampleService 类中删除 @Service 注释并将其作为 bean 添加到我的 AppConfig 类中时,它可以正常工作:
@Configuration
public class AppServiceConfig {
public AppServiceConfig() {
}
@Bean(name="sampleService")
public SampleService sampleService(){
return new SampleService();
}
}
这些类位于不同的包中。我没有使用@ComponentScan。相反,我使用的是@SpringBootApplication,它会自动执行此操作。但是,我也尝试使用 ComponentScan,但没有帮助。
我在这里做错了什么?
【问题讨论】:
-
你能展示你的
Application类(使用main方法的那个)吗? -
我已经用主类的代码更新了我的问题。
-
@drunkenfist 为什么要关闭上下文?你知道它会破坏所有的豆子仪式。
-
@drunkenfist 起初我无法重现此问题,使用与您发布的代码几乎相同的代码。然后在某个阶段,我意识到当我添加
@Service注释并点击快速导入时,我有两个选择。所以有一个 second@Service来自我在我的 pom 中的一些依赖,在这种情况下是spring-boot-starter-jersey但可能还有其他的。这听起来很遥远,但您能检查一下您的@Service的确切导入吗? -
我输入了一个类似的例子,一切都很完美。如上所述,您可以检查您导入的 @Service 注释的完全限定包名称吗?
标签: spring spring-mvc annotations spring-boot