Java Spring bean with private constructor

前端 未结 5 1444
终归单人心
终归单人心 2020-12-04 17:49

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.

相关标签:
5条回答
  • 2020-12-04 18:09

    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.

    0 讨论(0)
  • 2020-12-04 18:16

    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.

    0 讨论(0)
  • 2020-12-04 18:18

    Yes ! Spring can access private constructor. It will works internally like below code.

           try{
        Class c= Class.forName("A"); // A - className
        Constructor c1[]=c.getDeclaredConstructors();
        c1[0].setAccessible(true);
        A a= (A)c1[0].newInstance();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-04 18:19

    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.

    0 讨论(0)
  • 2020-12-04 18:30

    You would normally have a static factory method in such beans, you can specify that method for spring to get an instance of that bean. See 3.3.1.3 here. This is the way it's recommended by Spring, rather than going against visibility restrictions.

    0 讨论(0)
提交回复
热议问题