Announcement Announcement Module
Collapse
No announcement yet.
Accessing spring beans in static class Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Accessing spring beans in static class

    I have a Util class which have some static methods. I want to use spring beans, so i have added few service classes as beans in my util class. As far as i know its not a good practice to use spring beans as a static fields. But is there any way to access spring beans in a static method?

    My example:
    Code:
    public class TestUtils {
    
       private static testBean;
    
       public void setTestBean(TestBean testBean) {
         TestUtils.testBean = testBean;
       }
    
      public static String getBeanDetails() {
        return beanName = testBean.getDetails();
      }
    }
    I had seen in many forms that this is not a best practice, can some one help me how can i handle this type of scenarios?

    My xml has below value:
    Code:
    <bean id="testUtils" class="com.test.TestUtils">
     <property name="testBean" ref="testBean" />
    </bean>

  • #2
    You might consider the factory-method. See the docs http://static.springsource.org/sprin...tml/beans.html sec 3.3.2.2 Instantiation with a static factory method. Note that there seems to be 3 ways to create/manage your own factory with Spring. The next section (3.3.2.3) describes factory creation using non-static methods and there is yet a 3rd way by which you implement a FactoryBean interface as well. The first should suffice for you.

    Generally speaking if you can refactor your classes and remove static methods you would be better served by letting Spring manage your beans as singletons (default) or prototype scope if you need a new instance of a bean per invocation of .getBean or through dependency injection to other classes. See also Request and Session scoping for web apps if applicable.

    Comment

    Working...
    X