【问题标题】:Spring boot 2.1.4 Autowired works during startup but not when create new Pojo instanceSpring boot 2.1.4 Autowired 在启动期间有效,但在创建新 Pojo 实例时无效
【发布时间】: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


【解决方案1】:

我想我现在明白了 - IoC 将在启动时跟踪在 IoC 容器中创建的组件 - 其他一切都没有 谢谢你们 伊万

【讨论】:

    【解决方案2】:

    您的方法不正确。 带着你最初的问题 - 第 1 部分: 您正在自己创建new Pojo()。所以它不会自动注入是吗?我猜你已经明白了。

    第 2 部分: 您正在从 HTTP 请求正文创建 Pojo,而不是从容器创建。这意味着您有一个具有 Pojo 结构的 Json 请求,并且您希望它能够自动装配。回归基础:Autowire 仅在您自动装配或注入组件或父对象依次注入子组件时才有效。 更正您的 Json 请求!

    【讨论】:

    • 您能否详细说明如何更正 JSON 请求?感谢您的帮助!
    【解决方案3】:

    你要考虑的事情是当你想使用 spring 依赖注入 总是让spring容器通过@Autowire或'SpringContext'创建对象,否则它不会工作。要在这里解决您的问题,您还必须使用 @Autowire 在 run 方法中注入 Pojo。

    【讨论】:

    • 感谢您的回答,它确实主要工作。事实上,我最初的问题在于其余控制器 - 见下文 - 我假设这段代码在 Spring 上下文中?当我传递正确的 JSON 但未注入配置时,p 会被 Spring 自动实例化
    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多