我确实有一个用@Configuration
注释的简单类>
@ConfigurationProperties("sample") @Configuration public class Sample { private String username; private String password; private String url; //Implementation }
为了获得我的Web应用程序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 }
任何帮助plzz吗?
我确实有一个用@Configuration @ConfigurationProperties(“ sample”)注释的简单类,@Configuration公共类Sample {private String username;私有字符串密码; ...
更改@ConfigurationProperties("sample") @Configuration