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(); } }
Posted on June 28, 2011, in spring and tagged spring. Bookmark the permalink. 2 Comments.
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?
Agreed that its an antipattern but still at times we have to follow them. I just noted down a way to implement it when we need it 🙂