Shubham Chouksey
Shubham Chouksey

Reputation: 7

Null Pointer Exception in @Autowired Annotation

I know there are still a lot of sources that have already answered this question. But still, there are some resolved issue and getting NULL Pointer Exception Application.java File

package com.shubham.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.shubham.demo.producer.ProducerMain;

@SpringBootApplication
public class DemoApplication {
    
    
    @Autowired 
    private static ProducerMain producerMain; 
    
    public ProducerMain getProducerMain() {
        return producerMain;
    }
    public void setProducerMain(ProducerMain producerMain) {
        DemoApplication.producerMain = producerMain;
    }
    
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        producerMain.StartProducer();   // ---> Getting Null Pointer Exception 
    }

}

Producer.Main class

package com.shubham.demo.producer;

@Configurable 
@Component 
public class ProducerMain {
    
    public ProducerMain() {
        super();
    }
    public void StartProducer() {
        System.out.println("Started the Producer");
    }
    
}

Upvotes: 0

Views: 2838

Answers (1)

orser
orser

Reputation: 164

You are getting Null Pointer because your field annotated with @Autowired is a static field. Spring does not support autowiring static fields.

Try adding @Autowired to your setter method instead to the field.

private static ProducerMain producerMain; 

public ProducerMain getProducerMain() {
    return producerMain;
}
@Autowired 
public void setProducerMain(ProducerMain producerMain) {
    DemoApplication.producerMain = producerMain;
}

Upvotes: 2

Related Questions