Announcement Announcement Module
Collapse
No announcement yet.
How to ensure that a bean can not be modified? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to ensure that a bean can not be modified?

    I want to configure a bean with Spring using normal XML configuration files.

    However, once the bean has been set by Spring, I want to guarantee that the bean can never be modified again.

    I cant make things final inside or else Spring cant set them.

    What's good design pattern for this that is proven and works.

    Thanks for the help.

  • #2
    "Final" implies that the value will be assigned during the creation of a final object and can not be modified after that. Setter method executed by Spring is an attempt to modify the value which you can not do (according to Java specification - not Spring). Final fields are not assignable in other words without Spring Java will give you a compile error (see below)
    Code:
            private final Test2 test2;
    	
    	public void setTest2(Test2 test2) {
    		this.test2 = test2;
    	}
    
    
    The blank final field test2 may not have been initialized
    I am not sure what exactly are you trying to achieve, but if you simply want to be able to initialize the property once using Spring something like this will work just fine:
    Code:
            private Test2 test2;
            public void setTest2(Test2 test2) {
    		if (test2 == null){
    			this.test2 = test2;
    		}
    	}
    The field is not final but it will only be set once as you can see.

    NOTE: Depending on other factors there could be a concurrency issue, but that is a different topic

    Hope it helps
    Last edited by oleg.zhurakousky; Jan 10th, 2008, 09:14 AM.

    Comment


    • #3
      I want to guarantee that once a property is set, it can never be set again.

      What you did works but you would have to do that for all your set methods if you wanted to make sure that the bean is not changed.

      Comment


      • #4
        Originally posted by LordHalbert View Post
        What's good design pattern for this that is proven and works.
        The perfect use case for constructor injection - where you can make fields final. Spring supports constructor injection.

        Joerg

        Comment

        Working...
        X