简体   繁体   English

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

[英]spring application context not finding configuration bean

I have a configuration class:我有一个配置类:

@Configuration
public class MyConfig {
    @Value(value = "${com.test.myValue")
    private String myValue;
    
    public String getMyValue() {
        return myValue;
    }
}

And a non-bean class that use it:以及使用它的非 bean 类:

public class MyPOJO {
    private static MyConfig config = SpringContext.getBean(MyConfig.class);
    
    public String getMyValue() {
        return config.getMyValue();
    }
}

And this is the SpringContext class that I use to get the bean:这是我用来获取 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;
    }
}

but when I run this code:但是当我运行这段代码时:

MyPOJO pojo = new MyPOJO();
String value = pojo.getMyValue();

it fails on NullPointerException on return config.getMyValue();它在返回config.getMyValue();在 NullPointerException 上失败config.getMyValue(); which means config is null and wasn't created.这意味着 config 为空且未创建。

what could be the issue?可能是什么问题?

note that I don't believe it's an issue with component scan since i have an annotation that scan the entire package.请注意,我不认为这是组件扫描的问题,因为我有一个扫描整个包的注释。

You have mistakes in the MyConfig class:您在MyConfig类中有错误:

  1. There is no closing curly bracket }没有右大括号}
  2. Two different types for the myValue . myValue两种不同类型。
@Configuration
public class MyConfig {
    @Value(value = "${com.test.myValue}")
    private Integer myValue;

    public Integer getMyValue() {
        return myValue;
    }
}

Also, it's important to know the context when you create the POJO.此外,在创建 POJO 时了解上下文也很重要。 You should ensure that POJO creation is fulfilled before the Spring context is ready.您应该确保在 Spring 上下文准备好之前完成 POJO 创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM