Is possible in Spring that class for bean doesn't have public constructor but only private ? Will this private constructor invoked when bean is created? Thanks.
The decision to go with package-private visibility was made simply because private visibility is not allowed for @Bean methods due to CGLIB constraints.
Yes, Spring can invoke private constructors and instantiate object.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class.
Class. getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor.
Yes, Spring can invoke private constructors. If it finds a constructor with the right arguments, regardless of visibility, it will use reflection to set its constructor to be accessible.
You can always use a factory method to create beans rather than relying on a default constructor, from The IoC container: Instantiation using an instance factory method:
<!-- the factory bean, which contains a method called createInstance() --> <bean id="serviceLocator" class="com.foo.DefaultServiceLocator"> <!-- inject any dependencies required by this locator bean --> </bean> <!-- the bean to be created via the factory bean --> <bean id="exampleBean" factory-bean="serviceLocator" factory-method="createInstance"/>
This has the advantage that you can use non-default constructors for your bean, and the dependencies for the factory method bean can be injected as well.
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