3

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) {
}
BigJ
  • 1,990
  • 2
  • 29
  • 47
  • declare this string in application.properties and then use `@Value` to get it in MyClass. Then you don't need to pass any string – pvpkiran Feb 01 '18 at 14:55
  • I've read about the @Value option, but I want the string value to be different for each prototype bean. – BigJ Feb 01 '18 at 14:57
  • try to make beanFactory get MyClassBuilder then call your MylassBuilder.build(String mandatoryString); – Monsif Mabrouk Feb 01 '18 at 15:05
  • from where are you calling getBean? can you put that code. YOu can autowire userRepository in that class and pass that to getBean – pvpkiran Feb 01 '18 at 15:16

0 Answers0