【问题标题】:Using @Autowired in the spring main application在spring主应用程序中使用@Autowired
【发布时间】:2020-07-27 07:00:18
【问题描述】:

我创建了一个 spring 项目,在这里我实现了命令行运行器,因为我创建的应用程序需要在控制台上运行。因此,在 run 方法中,我创建了另一个类的对象并调用该方法来执行应用程序。

因此,在创建对象时,我必须将其设为 Autowired,并将相关类设为组件。
是做代码的好编码方式还是有其他方法可以避免空指针异常。

而且我对为什么放置 Autowired 的了解并不是 100% 确定的,我认为 Autowired 关键字注入了 Menu 类的 bean,因此可以调用该类的方法和变量。对吗?

主类

    @SpringBootApplication
    public class DemoApplication implements CommandLineRunner {

    @Autowired
    private Menu obj;

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

    @Override
    public void run(String... args) throws Exception {
        obj.start();
    }
    }

菜单类

    @Component
    public class Menu {
        
        public void start(){
            //implementation 
        }
    }

【问题讨论】:

  • 没有问题,看起来还不错。你有什么问题吗?
  • 不,没有问题,它工作正常,我只需要知道我所做的是否正确,以及它是否是一种好的编码方式。
  • 是的,这是管理代码中依赖关系的一种好方法。

标签: java spring spring-boot


【解决方案1】:

我觉得这样好多了

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

    @SuppressWarnings("resource")
    public static void main(final String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication, args);

        context.getBean(Menu).start(); // <-- here
    }
}

希望有用

【讨论】:

    【解决方案2】:

    我认为您可以在方法上使用 @PostConstruct 注释 而不是 命令行运行器 在运行应用程序后执行代码。 p>

    示例:

    @PostConstruct
    public void init(){
       obj.start();
    // or any code that use @autowired injection
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2017-04-09
      • 2020-10-04
      相关资源
      最近更新 更多