I have a prototype bean that autowires a bean in the constructor:
@Component
@Scope("prototype")
public class MyClass {
// Autowired annotation not needed in Spring 5
public MyClass(UserRepository userRepository) {
}
}
This bean is created with:
MyClass myClass = beanFactory.getBean(MyClass.class);
This all goes fine. But now I want to include a parameter when I create the bean:
MyClass myClass = beanFactory.getBean(MyClass.class, "just-a-string");
// Bean constructor:
public MyClass(String str, UserRepository userRepository) {
}
But this results in the following error:
Error creating bean with name 'myClass' ... Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
How should I combine constructor dependency injection with simple arguments?
Edit
As the error indicates, no matching constructor is found. When I use this to create to bean:
MyClass myClass = beanFactory.getBean(MyClass.class, "just-a-string", null);
The bean is created with success, but of course I'm getting a null pointer later.
Edit 2
If I used field injection this situation would be avoided, but as I understand field injection is discouraged:
@Autowired
UserRepository userRepository
public MyClass(String str) {
}