Static Field Injection In Spring

Injecting static fields in a spring bean doesn’t work by simply adding @Autowired annotation as below.

@Component
public class MessageHelper {
    @Autowired
    private static MessageBean messageBean;

    public static void msg() {
        messageBean.display();
    }
}

It works either by having constructor or setter based injection.

@Component
public class MessageHelper {
    private static MessageBean messageBean;

    @Autowired
    private void setMessageBean(MessageBean messageBean) {
        MessageHelper.messageBean = messageBean;
    }

    public static void msg() {
        messageBean.display();
    }

}
Advertisements

Posted on June 28, 2011, in spring and tagged . Bookmark the permalink. 2 Comments.

  1. Why would you do that? I know that it works. I have pieces of code like that in legacy project but don’t you think its an antipattern?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: