【发布时间】:2018-02-02 10:31:18
【问题描述】:
我正在 Spring Boot 中创建应用程序。我创建了这样的服务:
@Service
public class MyService {
@Value("${myprops.hostname}")
private String host;
public void callEndpoint() {
String endpointUrl = this.host + "/endpoint";
System.out.println(endpointUrl);
}
}
此服务将连接到将部署的其他应用程序(也是由我开发的)的 REST 端点。这就是为什么我想在 application.properties 文件中自定义主机名(-default、-qa、-dev)。
我的应用程序构建并运行良好。我通过创建调用此服务的控制器对其进行了测试,它使用来自 application.properties 的正确属性填充 host 字段。
当我尝试为这个类编写测试时出现问题。 当我尝试这种方法时:
@RunWith(SpringRunner.class)
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void callEndpoint() {
myService.callEndpoint();
}
}
我收到异常:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ge.bm.wip.comp.processor.service.MyServiceTest': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ge.bm.wip.comp.processor.service.MyService' available: expected at least 1 bean which qualifies as autowire candidate.
还有一些嵌套的异常。如果有帮助,我可以发布它们。 我想由于某种原因 SpringRunner 没有在 Spring 上下文中启动这个测试,因此看不到 bean MyService。
有谁知道如何解决?我尝试了正常初始化:
private MyService myService = new myService();
但是host 字段是null
【问题讨论】:
标签: java spring spring-boot junit dependency-injection