【问题标题】:SpringBoot @Autowire why does this example work?SpringBoot @Autowire 为什么这个例子有效?
【发布时间】:2020-09-13 22:35:08
【问题描述】:

我已经创建了这个类:

import org.springframework.stereotype.Component;

...

@Component("notTheNameTestMe") //shouldnt this only work with testMe ?
public class TestMe {

    public void showMsg() {
        System.out.println("Autowiring works");
    }

}

我在第二类(或更好:控制器)中以这种方式使用它:

import com.example.TestMe; //shouldnt this be not necessary with autowire? But getting error else...

...

@Autowired
private TestMe testMe;

...

this.testMe.showMsg();

但这很好用(所以也许我在这里没有真正使用自动装配?),如果我将整个 TestMe 类重命名为 TestMeSomething(如果我在第二个类中调整导入),它甚至可以工作 我真的不明白@Autowired 做了什么。我以为它只是扫描 SpringBoot 组件(由 @Component() 中的字符串命名,当它找到匹配项时,它会注入依赖关系。但在我的示例中,匹配是不可能的,我仍然可以看到消息“自动装配工作”在控制台中。如果我真的在这里使用 autowire 或者这不应该是这样的吗?我以错误的方式理解了什么?那么使用 new TestMe() 有什么区别?我已经依赖于导入或者?所以不是真正的依赖注入,或者?

【问题讨论】:

标签: java spring-boot autowired


【解决方案1】:

Spring 未对 @Component 注释中的名称进行操作。而是使用类的名称。它只是找到一个名为 TestMe 的类,因为这是您使用 @Autowired 注释的变量的类型。

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 2011-11-11
    • 2020-10-19
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多