I'm having trouble injecting the Bean type to a constructor parameter from a property file. I am able to inject it by directly passing the value to @Qualifier("beanName") as follows.
@Component("circle")
public class Circle implements Shape {
}
@RestController
class MyController {
private final Shape shape;
@Autowired
public MyClass(@Qualifier("circle")
Shape shape) {
this.shape = shape;
}
}
However, the below code samples do not work.
This returns Null.
@RestController
class MyController {
private final Shape shape;
@Autowired
public MyClass(@Qualifier("${shape}")
Shape shape) {
this.shape = shape;
}
}
Tried using @Resource(name="${shape}") in place of @Qualifier as mentioned here ( Spring: Using @Qualifier with Property Placeholder ) but get the compiler error " '@Resource' not applicable to parameter "
@Resource("${shape}") gives the error " Cannot find method 'value' "
This does not work too:
@RestController
class MyController {
@Value("${shape}")
private final String shapeBean; //Compiler error : "Variable 'shapeBean' might not have been initialised"
//Not declaring shapeBean as final will give a compiler error at @Qualifier: "Attribute value must be constant"
private final Shape shape;
@Autowired
public MyClass(@Qualifier(shapeBean)
Shape shape) {
this.shape = shape;
}
}
The code below does not work too. Gives a compiler error at @Qualifier : "Attribute value must be constant".
@RestController
class MyController {
@Value("${shape}")
private final String shapeBean;
private final Shape shape;
@Autowired
public MyClass(@Qualifier(shapeBean)
Shape shape) {
this.shape = shape;
}
}
Also tried the following. Both throw a NullPointerException on attempting to access shape.
@Resource(name="${shape}")
private Shape shape; // In addition, throws a warning saying, "Private field 'shape' is never assigned"
@Autowired
@Resource(name="${shape}")
private Shape shape;
If the constructor parameter was a primitive or a String, I could just use the @Value("${shape}") and inject the value to the variable. But since it's a Class I am not sure how to get it done.
Could someone please tell me if I have configured incorrectly or what I'm supposed to do?