@Autowired注解中的空指针异常
Null Pointer Exception in @Autowired Annotation
我知道还有很多资源已经回答了这个问题。但是,仍然有一些已解决的问题并出现 NULL Pointer Exception
Application.java 文件
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");
}
}
您得到空指针是因为您用@Autowired 注释的字段是静态字段。 Spring 不支持自动装配静态字段。
尝试将 @Autowired 添加到您的 setter 方法而不是字段。
private static ProducerMain producerMain;
public ProducerMain getProducerMain() {
return producerMain;
}
@Autowired
public void setProducerMain(ProducerMain producerMain) {
DemoApplication.producerMain = producerMain;
}
我知道还有很多资源已经回答了这个问题。但是,仍然有一些已解决的问题并出现 NULL Pointer Exception Application.java 文件
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");
}
}
您得到空指针是因为您用@Autowired 注释的字段是静态字段。 Spring 不支持自动装配静态字段。
尝试将 @Autowired 添加到您的 setter 方法而不是字段。
private static ProducerMain producerMain;
public ProducerMain getProducerMain() {
return producerMain;
}
@Autowired
public void setProducerMain(ProducerMain producerMain) {
DemoApplication.producerMain = producerMain;
}