簡體   English   中英

spring 應用程序上下文未找到配置 bean

[英]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類中有錯誤:

  1. 沒有右大括號}
  2. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM