freshflesh
freshflesh

Reputation: 19

Spring Bean for static classes

I am trying to understand drawbacks of my design , below is my code

class Utils {
    public static SpringBean bean;
    public static void setBean(SpringBean b){
        bean = b;
    } 
    public static SpringBean getBean(){
        return bean;
    }
    public static Object getSomethingFromBean(){
        return bean.getSomethingFromBean();
    }
}

Below is my bean context xml

<bean id="utils" class="utils">
    <property name="bean" ref="springBean"></property>
</bean>

<bean id="springBean" class="SpringBean">
</bean>

I am doing this so I can directly call methods of utils class like ,

Utils.getSomethingFromBean();

Upvotes: 1

Views: 7152

Answers (1)

Jiri Tousek
Jiri Tousek

Reputation: 12440

The point of Spring is (simplifying here) to avoid accessing the services through static methods or singletons. All reasons for using Spring apply to why not to use this approach.

Also, having to instantiate a static-fields-only class is a good hint that you're doing something at least unusual.

And last, as presented it doesn't make sense to have the content of Utils static - you can do utils.getSomethingFromBean(); just as well if Utils is a normal bean with no static fields. If your intention is to be able to call Utils.getSomethingFromBean();, you should make utils Spring bean available to the caller rather than resorting to static methods.

Upvotes: 4

Related Questions