Java Spring bean with private constructor

前端 未结 5 1466
终归单人心
终归单人心 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: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();
        }
    

提交回复
热议问题