简体   繁体   中英

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:

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:

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(); which means config is null and wasn't created.

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:

  1. There is no closing curly bracket }
  2. Two different types for the 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. You should ensure that POJO creation is fulfilled before the Spring context is ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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