【发布时间】:2019-01-23 12:32:21
【问题描述】:
我有两个@Configuration 课程。我需要一个从一个配置类到另一个配置类的 bean。我已将配置 1 自动连接到 2。一切正常。执行单元测试时,出现以下异常。
setUpContext(com.trafigura.titan.framework.services.messaging.loader.SpringLoadTest)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.xxx.MessagingServicesConfig': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.EMSJMSConfig com.xxx.MessagingServicesConfig.emsJmsConfig;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type[com.xxx.EMSJMSConfig] 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)}
我还需要做些什么才能使其正常工作吗?
下面是测试设置。
@Configuration
@Import({MessagingServicesConfig.class,...,EMSJMSConfig.class
})
public class MessagingConfig {}
@Profile("EMS-MESSAGING")
@Configuration
public class EMSJMSConfig {
@Bean
public javax.jms.ConnectionFactory jmsSubscriberConnectionFactory() throws JMSException {
SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(tibjmsConnectionFactory());
return singleConnectionFactory;
}
}
@Configuration
public class MessagingServicesConfig {
@Autowired
private EMSJMSConfig emsJmsConfig;
@Bean(destroyMethod = "shutdown")
public MessagingService messagingService() throws JMSException {
...
ConnectionFactory cf=emsJmsConfig.jmsSubscriberConnectionFactory(); // Getting NPE at this line.
}
}
最后是测试类,
public class MessagingServicesConfigTest {
private MessagingServicesConfig config;
private EMSJMSConfig emsJmsConfig;
@BeforeMethod
public void setUp() throws Exception {
config = new MessagingServicesConfig();
... //what needs to be done here to have the EMSJMSConfig
}
@Test
public void testBuildsCorrectService() throws JMSException {
MessagingService service = config.messagingService();
...
}
}
【问题讨论】:
-
这无济于事,也没有加载配置。使用正确的
@ContextConfiguration注释来指定要加载的内容。 -
那么请告诉我如何加载它?
-
没有看到你现在在做什么很难说。但是您应该使用
SpringRunner来运行您的测试并使用@ContextConfiguration来指定要加载的类。
标签: java spring junit autowired