【问题标题】:Understanding Spring Boot @Autowired了解 Spring Boot @Autowired
【发布时间】:2016-11-23 09:48:06
【问题描述】:

我不明白 Spring Boot 的注释 @Autowired 是如何正确工作的。这是一个简单的例子:

@SpringBootApplication
public class App {
    @Autowired
    public Starter starter;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    public App() {
        System.out.println("init App");
        //starter.init();
    }
}

--

@Repository
public class Starter {
    public Starter() {System.out.println("init Starter");}
    public void init() { System.out.println("call init"); }
}

当我执行这段代码时,我得到了日志init Appinit Starter,所以spring 创建了这个对象。但是当我在App 中从Starter 调用init 方法时,我得到一个NullPointerException。除了使用注解@Autowired 来初始化我的对象之外,我还需要做些什么吗?

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [{package}.App$$EnhancerBySpringCGLIB$$87a7ccf]: Constructor threw exception; nested exception is java.lang.NullPointerException

【问题讨论】:

  • 根据你的 bean 的范围,因为 Spring Boot 应用程序被预先配置为使用包扫描,所以 spring 将创建你想要使用的 bean 的实例。但是,仅仅因为它已经被创建,并不一定意味着它已经被注入。

标签: java spring spring-boot


【解决方案1】:

当您从类App 的构造函数中调用init 方法时,Spring 尚未将依赖关系自动装配到App 对象中。如果你想在 Spring 完成创建和自动装配 App 对象后调用此方法,则添加一个带有 @PostConstruct 注释的方法来执行此操作,例如:

@SpringBootApplication
public class App {
    @Autowired
    public Starter starter;

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

    public App() {
        System.out.println("constructor of App");
    }

    @PostConstruct
    public void init() {
        System.out.println("Calling starter.init");
        starter.init();
    }
}

【讨论】:

  • 这是有道理的。现在它的工作,谢谢。所以当你想访问一个自动装配的对象时,你总是需要使用@PostConstruct注解。
  • 请参阅 Oliver Gierkes 的博文:olivergierke.de/2013/11/why-field-injection-is-evil
  • @daniel.eichten 我同意构造函数注入比字段注入更好,但这是与这个问题有关的另一个问题。
猜你喜欢
  • 2014-12-15
  • 1970-01-01
  • 2016-04-20
  • 2018-07-01
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
相关资源
最近更新 更多