Results 1 to 2 of 2

Thread: static member variable in a singleton Spring bean

  1. #1

    Default static member variable in a singleton Spring bean

    Code:
    public class MySpringBean {
    
    	private static MyDIClass myDIClass;
    	// setter for myDIClass
    
    	static{
    
                     // myDIClass is referenced here
                 }
    }
    I have a static attribute (myDIClass) in a singleton Spring bean class called MySpringBean. The reason for defining myDIClass as static so that I can reference it within the static block.

    Also, note that the value of myDIClass is not bound to change e.g., toString()/equals() on it will always be the same (e.g. value as Apple) across the application, accross each and every invocation.

    My question:
    1. Am I running into any violation by declaring myDICass as static, considering its value will always be the same for all the invocations across the application?

  2. #2
    Join Date
    May 2007
    Location
    Saint Petersburg, Russian Federation
    Posts
    1,189

    Default

    I have a question too - how does that relate to the 'AOP (Aspect Oriented Programming)' (current forum name)?

    P.S. static singletons are almost always a bad idea because they add coupling to the code and make it much harder to maintain it and write unit tests. However, singleton idea (one object per-application) is very good and reasonable. Spring defines a notion of bean scope, so, you can just declare your 'MyDIClass' bean as a singleton-scoped and let the container create it's single instance and inject to all another target beans.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •