Java Spring bean with private constructor

前端 未结 5 1457
终归单人心
终归单人心 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:16

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

    Bean definition file:

    
            
        
    

    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.

提交回复
热议问题