Reputation: 193
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?
Upvotes: 0
Views: 55
Reputation: 23119
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.
Upvotes: 1