0

I have a Spring Boot application, in which I use "prototype" beans. I know it is possible to inject parameters through constructors arguments but I would like to avoid the approach, as I have a number of additional configuration parameters, including other Beans AND my per-instace parameters.

public class FooBar {
    // singleton beans that are shared between multiple instances of this class
    private FooRepository fooRepository;
    private BarRepository barRepository;

    // instance specific settings that are SPECIFIC to the instance of this class   
    private String fooParameter;
    private String barParameter;
    private String parameterX;
    private String parameterY;
    private String parameterZ;
    //...
}


@Configuration
public class AppConfig {

    /* @Bean definition of FooRepository, BarRepository etc */

   @Bean
   @Scope(value = "prototype")
   public FooBar getFoobar(
        FooRepository fooRepository, BarRepository barRepository,
        String fooParameter, String barParameter, String parameterX /* ... */) {
       // works, but I want to avoid something like this
       return new new Foobar(fooRepository, barRepository, 
                    fooParameter, barParameter, parameterX, /* ... */);
   }

   @Bean
   @Scope(value = "prototype")
   public FooBar getFoobar(HashMap<String, String> moreParameters) {
       Foobar foobar = new Foobar();

       // inject parameters without having to implement setter calls
       // I want to inject BOTH Spring Beans here and some config parameters    

       return foobar;
   }
}

Is there any way to get Spring to do the Autowiring from its internal set of Beans AND my provided parameters as well? I want to avoid having to setter calls completely.

Peter G. Horvath
  • 535
  • 1
  • 3
  • 15
  • If I understand you correctly, you want the class `FooBar` to possibly have two sets or more of different dependencies wired but you don't want to do them via `constructor` or `setter` methods. I don't think there's a way. Is this design the only way to achieve what you want? – Tan Kim Loong May 16 '20 at 09:45

1 Answers1

0

No, unfortunately there is no other way to make dependency injection! Even in the official Spring documentation it is clearly indicated that the implementation takes place according to the constructor or the setter, BUT what is extremely important, attention is paid specifically to SETTER.

@Autowirder
public void settter(){}
Artur Vartanyan
  • 589
  • 3
  • 10
  • 35