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,
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).
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.
If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.
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 .
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}); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With