英文:
ApplicationContext.getAppContext().getBean("jBeanName") return null in Junit test
问题
我确实有一个用 @Configuration
注释的简单类
@ConfigurationProperties("sample")
@Configuration
public class Sample {
private String username;
private String password;
private String url;
//Implementation
}
为了获取我的 web 应用程序 beans 文件,我创建了这个类
@Component
public class AppSpringContext implements ApplicationContextAware {
private static ApplicationContext context;
/**
* 如果存在,返回给定类类型的 Spring 管理的 bean 实例。否则返回 null。
*
* @param
* @return
*/
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
// 存储 ApplicationContext 引用以便以后访问所需的 bean
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"); // 返回 NULL 对象
}
return cfg;
}
// 其余实现
}
有任何帮助吗?
英文:
I do have this simple class annotated with @Configuration
@ConfigurationProperties("sample")
@Configuration
public class Sample {
private String username;
private String password;
private String url;
//Implementation }
In order to get my web app beans file, I created this class
@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;
}
}
When I tried to instantiate the sample class in the test class I got a null pointer exception although I was able to instantiate it successfully in the main class
@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
}
Any help plzz ??
答案1
得分: -1
更改为 @ConfigurationProperties("sample") @Configuration
。
英文:
change @ConfigurationProperties("sample") @Configuration
专注分享java语言的经验与见解,让所有开发者获益!
评论