![](/img/trans.png)
[英]How to test @Configuration and @Bean in a Spring Boot Application?
[英]spring application context not finding configuration bean
我有一個配置類:
@Configuration
public class MyConfig {
@Value(value = "${com.test.myValue")
private String myValue;
public String getMyValue() {
return myValue;
}
}
以及使用它的非 bean 類:
public class MyPOJO {
private static MyConfig config = SpringContext.getBean(MyConfig.class);
public String getMyValue() {
return config.getMyValue();
}
}
這是我用來獲取 bean 的 SpringContext 類:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext context;
/**
* Returns the Spring managed bean instance of the given class type if it exists. Returns null
* otherwise.
*
* @param beanClass
* @return
*/
public static <T extends Object> T getBean (Class<T> beanClass) {
return context.getBean(beanClass);
}
@Override
public void setApplicationContext (ApplicationContext context) throws BeansException {
SpringContext.context = context;
}
}
但是當我運行這段代碼時:
MyPOJO pojo = new MyPOJO();
String value = pojo.getMyValue();
它在返回config.getMyValue();
在 NullPointerException 上失敗config.getMyValue();
這意味着 config 為空且未創建。
可能是什么問題?
請注意,我不認為這是組件掃描的問題,因為我有一個掃描整個包的注釋。
您在MyConfig
類中有錯誤:
}
myValue
兩種不同類型。@Configuration
public class MyConfig {
@Value(value = "${com.test.myValue}")
private Integer myValue;
public Integer getMyValue() {
return myValue;
}
}
此外,在創建 POJO 時了解上下文也很重要。 您應該確保在 Spring 上下文准備好之前完成 POJO 創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.