I've recently came across a behavior in Spring framework which left me very puzzled: if two classes have the same simple name (but are from different packages), and both are marked with the @Component
annoation, then any attempt to mark a variable of the type of one of them with @Autowired
will result in an exception, since there are 2 different Beans declared with the desired name. Simply put - the @Component
annotation uses the Class' simple name instead of its full name (this is also mentioned in this question).
Is there a reason why Spring works this way? From what I understood, the whole point of dependency injection is that you can receive an object of the appropriate type without knowing how to create it, and so forcing the receiver of the dependency to know the source of the dependency through annotations such as @Qualifier
even though there is only 1 truly relevant option really confuses me.
It works fine. First component:
package com.example.demo.component1;
import org.springframework.stereotype.Component;
@Component
public class SimpleComponent {
public String action() {
return "imSimpleComponent";
}
}
Second component:
package com.example.demo.component2;
import org.springframework.stereotype.Component;
@Component("SimpleComponent2")
public class SimpleComponent {
public String action() {
return "imSimpleComponent2";
}
}
Controller:
package com.example.demo.controller;
import com.example.demo.component1.SimpleComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ResourceController {
@Autowired
private SimpleComponent simpleComponent;
@Autowired
private com.example.demo.component2.SimpleComponent simpleComponent2;
@RequestMapping("/home")
public String hello() {
return simpleComponent.action() + "_" + simpleComponent2.action();
}
}
http://localhost:8080/home return:
imSimpleComponent_imSimpleComponent2