javaspringdependency-injectionautowired

Can you access @Autowire'd fields through static references?


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.


Solution

  • Just annotate the constuctor of Factory with @Autowired

    @Component
    public class Factory {
    
        private static ProductService productService;
    
        @Autowired
        public Factory(ProductService productService) {
            Factory.productService = productService;
        }
    
        public static Product produce() { productService.produce(); }
    }