Let's say you have the following setup:
public class Producer {
public Product produce() { /* Creates some product */ }
}
@Service
public class ProductService {
@Autowired
private Producer producer;
public Product produce() { producer.produce(); }
}
public class Factory {
private static ProductService productService = new ProductService();
public static Product produce() { productService.produce(); }
}
When I call Factory.produce(), I get a NullPointerException, because producer is null. Since producer itself is not a static field, I was hoping that by setting it up this way, I could use Springs dependency injection in a static context. Did I make a mistake, or is this simply not possible?
For context: In my real application, Factory holds multiple services, which in turn each hold multiple producers. I chose this structure so the rest of my application only needs to access the Factory, with all of the complexity behind it being abstracted by it.
Just annotate the constuctor of
Factorywith@Autowired