1

My xml looks like this:

<bean name="subscriberStore" class="java.util.HashSet" scope="singleton"/> 

And I have the following code:

@Value("#{subscriberStore}")
private static HashSet<Subscriber> subscriberStore;

However, later in the above class, when I call methods on subscriberStore I get a null pointer exception. I've tried using @Autowired and @Resource in place of @Value .. above but it makes no difference.

Anyone have any ideas why the subscriber store is not getting initialized?

Thanks!

skaffman
  • 398,947
  • 96
  • 818
  • 769
Rory
  • 1,805
  • 7
  • 31
  • 45
  • Is the class in which you're using the @Autowired annotation etc being loaded by Spring, or by you? If it's not being loaded by Spring, then no dependency injection will take place fwir. – mcfinnigan Feb 24 '12 at 14:06
  • 1
    Many duplicates, including http://stackoverflow.com/questions/7657168/static-fields-autowiring-in-spring http://stackoverflow.com/questions/1018797/autowired-static-field-spring-2-5 http://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field and especially http://stackoverflow.com/questions/2763279/injecting-values-for-static-constants-in-spring – skaffman Feb 24 '12 at 14:08
  • @skaffman My question wasn't about autowiring statics, it was about autowiring a collection, which just happens to be a static. In this case I though the problem was with it being a collection - not a static, as per my question title. – Rory Feb 24 '12 at 14:12
  • @Rory: The reason it doesn't work is because it's static, not because it's a collection. Failure to autowire collections resilts in an exception, whereas failure to autowire statics results in a null. – skaffman Feb 24 '12 at 14:17
  • You could also try this trick: http://www.connorgarvey.com/blog/?p=105 – GreyBeardedGeek Feb 24 '12 at 14:20

1 Answers1

6

You cannot @Autowire static fields. Consider removing the static modifier, if possible.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
  • Thanks this worked - I suppose the static modifier is not strictly needed anyway, since subscriberStore is a Spring singleton, is this correct? – Rory Feb 24 '12 at 14:11
  • Sure...but just because it is a Spring singleton, doesn't mean that ***YOU*** cannot create an instance using the `new` operator... – nicholas.hauschild Feb 24 '12 at 14:18