【发布时间】: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