【发布时间】:2019-09-13 05:54:03
【问题描述】:
Spring boot 2.1.4 Autowired 在启动过程中运行良好,但在创建新 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 类定义
@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; }
主要
@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 似乎已实例化,但 @Autowired 似乎没有工作。
知道我做错了什么吗?
补充说明 谢谢你的回复——我知道 pojo 已经被 Spring 实例化了——谢谢你的澄清,我现在明白了。话虽如此,我对 RestController 有完全相同的问题 - 见下文。 p 被 Spring 自动映射到一个新的 Pojo,但是这个 pojo 中的配置不是自动装配的。
@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
}
【问题讨论】:
-
当然不会。 Spring 只会注入它创建的实例,如果您在 Spring 范围之外创建实例(就像您所做的那样),则不会注入任何东西。
-
明白,但我对 RestController 也有同样的问题 - 请参阅下面的代码示例,该示例也以空指针结尾。无论如何,感谢您的帮助!
标签: spring-boot autowired