Spring boot 2.1.4 Autowired works well during startup but not when create new Pojo instance, see code below
Pojo
@Component
public class Pojo {
private ConfigController c;
@Autowired
public void setProperty(ConfigController cp) { this.c = cp; }
public Pojo () {};
public String getVal() { return c.geItem1(); }
}
ConfigController class definition
@Configuration
@Component
public class ConfigController {
private String item1;
private String item2;
public ConfigController () {};
public String geItem1()
{ return this.item1; }
public void setItem1(String s)
{ this.item1 = s; }
Main
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
@Autowired
private ConfigController c;
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
@Override
public void run(String... args) {
Pojo p = new Pojo();
System.println(p.getVal()); // Runtime error here with java.lang.NullPointerException
}
}
p seems to be instantiated but @Autowired doesn;t seem to be working.
Any clue what I am not doing right?
Additional Note Thank you for your replies - I understand that the pojo has the be instantiated by Spring - thanks for the clarification, I get it now. Having said this, I have exactly the same issue with the RestController - see below. p is automatically mapped by Spring to a new Pojo but the configuration in this pojo is not autowired.
@RestController
public class MyController {
@GetMapping("/my-end-point")
OtherPojo getOtherPojo(@RequestBody Pojo p)
{
System.println(p.getVal()); // Runtime error here with java.lang.NullPointerException
// ... more code
}