繁体   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