首页 > 解决方案 > 无法自动接线

问题描述

使用 Spring Initializer 创建一个简单的 Spring Boot。我只在可用选项下选择 DevTools。

创建项目后,无需对其进行任何更改,即可正常运行程序。

现在,当我尝试在项目中进行一些自动装配时,它根本不起作用。我不明白。一直在这里查看以前的所有问题,这些问题都有解决方案,但没有一个有效,而且我在我的案例中所做的事情并不复杂,如下所示。请告知我所缺少的。

@SpringBootApplication
public class DemoApplication {

    //  @Autowired
    //  private static Maker maker; // Stopped using this cos I wanted to check if the autowiring is not working in this class only or anywhere. Turns out it is anywhere. 

        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
            Maker maker = new Maker();
            maker.printName(); // Fails cos of ServiceHelper Autowiring 
        }
    }


@Service
public class Maker {

    @Autowired
    private ServiceHelper serviceHelper;

    public void printName(){
        System.out.println("This is from the method body itself.");
        System.out.println("Auto wiring works cos I got this -> " + serviceHelper.help());
    }
}

@Component
public class ServiceHelper {
    public String help(){
        return "...FROM HELPER...";
    }
}

堆栈跟踪

在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl) 的线程“restartedMain”java.lang.reflect.InvocationTargetException 中的异常.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) 原因:java.lang。 NullPointerException at com.example.demo.services.Maker.printName(Maker.java:15) at com.example.demo.DemoApplication.main(DemoApplication.java:17) ... 还有 5 个

标签: javaspring-boot

解决方案


如果您使用new该 bean 不会添加到的关键字创建任何 bean Spring Application Context,这是@Autowire静态 bean的一种方法

@SpringBootApplication
public class DemoApplication {

    @Autowired
    private static Maker maker; 

    @Autowired
    private Maker tMaker;

    @PostConstruct
    public void init() {
    DemoApplication.maker = tMaker;
}

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        maker.printName();  
    }
}

或者您可以在创建时Autowire使用被注入Constructor的实例Maker作为构造函数的参数DemoApplication

@Autowired
public DemoApplication(Maker maker) {
    DemoApplication.maker = maker;
    }

或者您可以@Autowired在 setter 方法上使用,setter 方法在创建Maker时的实例中调用DemoApplication

@Autowired
public void setMaker(Maker maker) {
        DemoApplication.maker = maker
}

推荐阅读