0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.