【发布时间】:2020-04-07 12:08:06
【问题描述】:
我确实有这个用@Configuration注释的简单类
@ConfigurationProperties("sample")
@Configuration
public class Sample {
private String username;
private String password;
private String url;
//Implementation }
为了获取我的网络应用程序 bean 文件,我创建了这个类
@Component
public class AppSpringContext implements ApplicationContextAware {
private static ApplicationContext context;
/**
* Returns the Spring managed bean instance of the given class type if it exists.
* Returns null otherwise.
*
* @param
* @return
*/
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
// Store ApplicationContext reference to access required beans later on
AppSpringContext.context = context;
}
public static ApplicationContext getAppContext() {
return context;
}
}
当我尝试在测试类中实例化示例类时,我得到了一个空指针异常,尽管我能够在主类中成功实例化它
@RunWith(SpringJUnit4ClassRunner.class)
public class SampleTest {
private Sample getInstance(Sample cfg) {
if (cfg == null) {
cfg = (Sample) AppSpringContext.getAppContext().getBean("sample"); //returns NULL object
}
return cfg; }
//Rest of implementation
}
有什么帮助吗?
【问题讨论】:
-
你是如何确认
Samplebean 被创建的?当你用@SpringBootTest注释你的测试类时会发生什么?
标签: java spring-boot junit applicationcontext