简体   繁体   中英

Spring boot autowired class does not instantiate in regular class

So I have an external config class which injects variables with properties from my global.properties file.

I have no problem instantiating and accessing the object in my Spring boot main class but any other class in my project makes the external config object null.

This is what my external config class looks like

@Component
@PropertySource("classpath:global.properties")
public class ExternalConfig {

@Value("${developerName}")
private String developerName;

//getters and setters
public String getDeveloperName() {
    return developerName;
}

public void setDeveloperName(String developerName) {
    this.developerName = developerName;
}

}

This is my Spring boot main class

@SpringBootApplication
public class SpringBootMain implements CommandLineRunner {

@Autowired
private ExternalConfig externalConfig;

@Bean
ResourceConfig resourceConfig() {
    return new ResourceConfig().registerClasses(Version1Api.class, Paypal.class);
}

public static void main(String[] args) {
    SpringApplication.run(SpringBootMain.class);
}


@Override
public void run(String... args) throws Exception {
    // TODO Auto-generated method stub
    System.out.println("RUN METHOD");
    System.out.println(externalConfig.getDeveloperName());

}  

}

However if I try add this external config class to another class like my HTTP class

@Component
public class Http {
Http() {

}
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Version1Api.class);
@Autowired
private static ExternalConfig externalConfig;

public static void main(String[] args) throws IOException, URISyntaxException {
    logger.info("HTTP Class");
    logger.info(externalConfig.getDeveloperName());
}

The object is always null and gives me an error. What am I doing wrong? Should I be implementing my object in a different way?

Or should I be implementing my HTTP class in a different way?

All help would be greatly appreciated!

You could make this work by removing the @Autowired from the attribute and putting on a setter.

@Autowired
public void setExternalConfig(ExternalConfig externalConfig){
    Http.externalConfig = externalConfig;
}

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