Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring bean with private constructor

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.

like image 508
user710818 Avatar asked Aug 31 '11 08:08

user710818


People also ask

Can @bean method be private?

The decision to go with package-private visibility was made simply because private visibility is not allowed for @Bean methods due to CGLIB constraints.

Can IOC container instantiate beans using private constructors?

Yes, Spring can invoke private constructors and instantiate object.

Can constructor in Java be private?

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.

How do I invoke a private constructor?

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.


2 Answers

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.

like image 102
KevinS Avatar answered Sep 21 '22 05:09

KevinS


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.

like image 37
Matthew Farwell Avatar answered Sep 23 '22 05:09

Matthew Farwell