SpringBoot的 @Autowire 为什么这个示例有效?

huangapple go评论72阅读模式
英文:

SpringBoot @Autowire why does this example work?

问题

我创建了这个类:

import org.springframework.stereotype.Component;

...

@Component("notTheNameTestMe") // 这应该只对 testMe 起作用吧?
public class TestMe {

    public void showMsg() {
        System.out.println("自动装配生效了");
    }

}

我在第二个类(或者更好的说法是控制器)中这样使用它:

import com.example.TestMe; // 自动装配的话,这个应该不是必需的吧?但是如果不加会报错...

...

@Autowired
private TestMe testMe;

...

this.testMe.showMsg();

但是这个能正常工作(所以也许我这里并没有真正使用自动装配?),甚至如果我将整个 TestMe 类重命名为 TestMeSomething 也能工作(如果我在第二个类中调整导入的话)。
我真的不太明白 @Autowired 是做什么的。我原以为它只是扫描 SpringBoot 组件(通过 @Component() 中的字符串命名),当找到匹配时就注入依赖。但在我的例子中,匹配是不可能的,但我仍然可以在控制台看到 "自动装配生效了" 的消息。如果我真的在这里使用了自动装配,不应该是这样的,对吧?我理解错了什么?与直接使用 new TestMe() 有什么区别呢?我已经通过导入获得了依赖,对吗?所以这不算是真正的依赖注入,对吗?

英文:

I have created this class:

import org.springframework.stereotype.Component;

...

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

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

}

And I'm using it this way in a second class (or better: controller):

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

...

@Autowired
private TestMe testMe;

...

this.testMe.showMsg();

But this works perfectly (so maybe Im not really using autowire here?), it even works if I rename the whole TestMe class to TestMeSomething (if I adjust the import in the second class)
I dont really understand what @Autowired does. I thought it just scans for SpringBoot Components (which are named by the string in @Component() and when it finds a match it Injects the dependancy. But in my example the match is impossible and I still can see the message "Autowiring works" in the console. This shouldnt be like this if I would really use autowire here or? What am I understanding in a wrong way? What is the difference to using new TestMe() then? I have the dependancy already with the import or? So not a real dependancy injection, or?

答案1

得分: 1

春天并不在 @Component 注解中使用名称。相反,它使用类的名称。它只是在查找名为 TestMe 的类,因为那是您用 @Autowired 注释的变量的类型。

英文:

Spring is not operating on the name in the @Component annotation. Rather it's using the name of the class. It's simply finding a class named TestMe because that's the type of the variable you've annotated with @Autowired.

huangapple
  • 本文由 发表于 2020年9月13日 22:31:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63871929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定