我无法在主应用程序中使用自动接线

时间:2019-03-24 11:00:18

标签: java spring

我正在尝试在Running类中实例化customer类。尽管我标注了IT AS组件,但存在空指针异常

@Component
public class Running {
@Autowired
CustomerRepository cRep;

@Autowired InvoiceRepository iRep;


public void run() {
Customer c1=new Customer().setAge(25).setBalance(100).setName("xyz");
Customer c2=cRep.save(c1);

}


@SpringBootApplication
@EnableJpaRepositories

public class HelloWorldSpringBootApp {


    @Autowired  static
     Running r1;
public static void main (String[] args ) {

     SpringApplication.run(HelloWorldSpringBootApp.class, args);
     r1.run();
}

我在r1.run()上遇到了空指针异常。

1 个答案:

答案 0 :(得分:1)

Spring不允许您自动装配静态字段(请参见this question)。这是获取Running实例的正确方法:

@SpringBootApplication
@EnableJpaRepositories
public class HelloWorldSpringBootApp {


    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(HelloWorldSpringBootApp.class, args);
        Running r1 = applicationContext.getBean(Running.class);
        r1.run();
    }
}