Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set @Autowired constructor params as "required=false" individually

I'm using the @Autowired annotation under a @Configuration class constructor.

@Configuration public class MyConfiguration {     private MyServiceA myServiceA;    private MyServiceB myServiceB     @Autowired    public MyConfiguration(MyServiceA myServiceA, MyServiceB myServiceB){      this.myServiceA = myServiceA;      this.myServiceB = myServiceB;        } } 

As the Spring documentation sais, I'm able to declare whether the annotated dependency is required.

If I mark the @Autowired annotation under the constructor as required=false, I'm saying that the two services to be autowired are not required (as the Spring documentation says):

@Autowired(required = false) public MyConfiguration(MyServiceA myServiceA, MyServiceB myServiceB){   this.myServiceA = myServiceA;   this.myServiceB = myServiceB;    } 

From Spring documentation:

In the case of multiple argument methods, the 'required' parameter is applicable for all arguments.

How can I set the required attribute to each constructor parameter individually? Is necessary to use @Autowired annotation under every field?

Regards,

like image 578
jcgarcia Avatar asked Feb 09 '17 11:02

jcgarcia


People also ask

How do I set Autowired required false?

spring. beans. Class1' in your configuration. So, in case you are not sure about the availability of auto-wiring for the dependency or if the dependency is not mandatory, then you can specify @Autowired(required=false).

Can we do @autowired by constructor?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file.

How do you make auto writing as non mandatory for a specific bean property?

If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.

What will happen if I make @autowired as false?

By default, the @Autowired annotation implies that the dependency is required. This means an exception will be thrown when a dependency is not resolved. You can override that default behavior using the (required=false) option with @Autowired .


1 Answers

If you're using Java 8 and Spring Framework 4, you can use Optional.

@Autowired public MyConfiguration(Optional<MyServiceA> myServiceA, Optional<MyServiceB> myServiceB){   myServiceA.ifPresent(service->{this.myServiceA = service});   myServiceB.ifPresent(service->{this.myServiceB = service});    } 
like image 66
Strelok Avatar answered Sep 17 '22 17:09

Strelok