首页 > 解决方案 > 在spring boot中导入其他类和使用@autowired有什么区别?

问题描述

在 ClassA 的 Spring Boot 中,我们可以通过导入 ClassB 类来获取 ClassB 方法,这与我们对 @autowired 所做的行为相同。那么这两者之间的主要区别是什么。

标签: spring-boot

解决方案


import,顾名思义,就是 导入依赖。@Autowired创建该依赖项的实例并将其注入到我们的component.

假设我们有某个 B 类,例如:

class B {
    public B() {}

    public void sayHi() {
        System.out.println("Hello World");
    }
}

进口

import ClassB;

class A {
    private B bRef;

    public A() {}

    public void sayHi() {
        bRef.sayHi();
    }

    public static void main(String[] args) {
        A a = new A();
        a.sayHi(); // NullPointerException -> we bRef is null
    }
}

@自动连线

import ClassB;

@Component
class A {
    // autowiring member variables is considered bad but just to
    // illustrate the point
    @Autowired
    private B bRef;

    public A() {}

    public void sayHi() {
        bRef.sayHi();
    }

    public static void main(String[] args) {
        A a = new A();
        a.sayHi(); // Outputs: Hello World
        // bRef was constructed and injected into our component
    }
}

推荐阅读