Spring Boot:从Bean访问命令行args

Buc*_*uch 4 java properties spring-boot

我使用单个参数-filename运行spring boot应用程序。该文件包含我在运行时需要的一些属性。应用程序启动时会检查是否args.length==1

但是我需要在单个点上@Component添加此文件(属性)-带注释的Bean。

它是一种从文件中访问文件内容的方法吗?

Vai*_*das 5

在Spring中,有一个名为ApplicationArguments的bean ,它提供对用于运行应用程序的参数的访问。

@Component
public MyComponent {
    @Autowired
    private ApplicationArguments  applicationArguments;

    public void method() {
        List<String> filenameArgs = applicationArguments.getOptionValues("filename")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果以常规方法引用 ApplicationArguments,一切都会正常。但是当我在 init (@PostConstruct) 中使用它时,我得到 NullPointerException (2认同)