Java Spring bean with private constructor Java Spring bean with private constructor java java

Java Spring bean with private 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.


Yes, Private constructors are invoked by spring.Consider my code:

Bean definition file:

<bean id="message" class="com.aa.testp.Message">        <constructor-arg index="0" value="Hi Nice"/>    </bean>

Bean class:

package com.aa.testp;public class Message {    private String message;    private Message(String msg) {       // You may add your log or print statements to check execution or invocation        message = msg;    }    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }    public void display() {        System.out.println(" Hi " + message);    }}

The above code works fine. Hence, spring invoked the private constructor.