自动装配在springboot应用程序中不起作用 [英] Autowiring not working in springboot application

查看:94
本文介绍了自动装配在springboot应用程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JFrame创建一个Spring Boot应用程序.我可以在applicationContext中看到我的bean,但是它们没有自动连接.我找不到此问题的原因.有人可以帮我弄这个吗?

I am trying to create a Spring boot application with JFrame. I can see my beans in applicationContext but they are not getting autowired. I am unable to find the reason for this issue. Can someone help me with this?

这是代码:

JavauiApplication- 它同时显示userManager和userNameRepository是bean

JavauiApplication - it is showing both userManager and userNameRepository is beans

@SpringBootApplication
public class JavauiApplication implements CommandLineRunner {

    @Autowired
    private ApplicationContext appContext;

    public static void main(String[] args) {
        new SpringApplicationBuilder(JavauiApplication.class).headless(false).run(args);

        java.awt.EventQueue.invokeLater(() -> new InputNameForm().setVisible(true));
    }

    @Override
    public void run(String... args) throws Exception {

        String[] beans = appContext.getBeanDefinitionNames();
        Arrays.sort(beans);
        for (String bean : beans) {
            System.out.println(bean);
        }

    }
}

InputNameForm.java-> userManager为空

InputNameForm.java -> userManager coming null

@Component
public class InputNameForm extends javax.swing.JFrame {

    /**
     * Creates new form InputNameForm
     */
    public InputNameForm() {
        initComponents();
    }

    @Autowired
    UserManager userManager;

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
        userManager.setName(firstName.getText(), lastName.getText());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InputNameForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new InputNameForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField firstName;
    private javax.swing.JLabel firstNameLabel;
    private javax.swing.JTextField lastName;
    private javax.swing.JLabel lastNameLabel;
    private javax.swing.JButton submitButton;
    // End of variables declaration//GEN-END:variables
}

UserManager.java-> userNameRepository为空

UserManager.java -> userNameRepository is coming null

@Component
public class UserManager {

  @Autowired
  UserNameRepository userNameRepository;

  public void setName(String firstName, String lastName) {
    userNameRepository.save(new UserName(firstName, lastName));
    System.out.println(userNameRepository.findAllByFirstName(firstName));
  }
}

推荐答案

这是一个非常普遍的问题,由于新来者不了解IoC容器的工作原理而发生.

It's a very common problem and it occurs because newcomers don't understand how the IoC container works.

  1. 首先,BeanDefinitionReader从XML,注释(@Component@Service等),JavaConfig或Groovy脚本中读取有关您的bean的元数据.
  2. 有几个BeanPostProcessor负责读取您正在编写的所有这些Spring注释(@Autowired等).
  3. BeanFactory创建所有BeanPostProcessor,然后创建所有Bean.
  1. Firstly, BeanDefinitionReader reads metadata about your beans from XML, Annotations(@Component, @Service etc), JavaConfig or Groovy script.
  2. There are several BeanPostProcessor's which is responsible for reading all of these Spring annotation you're writing(@Autowired etc).
  3. BeanFactory creates all BeanPostProcessor's then it creates all of your beans.

如果通过new运算符创建具有@Autowired依赖项的bean,会发生什么情况?没什么,因为它实际上不是bean.您创建的对象与IoC容器无关.如果您用@Component(例如)标记了ApplicationContext,则可能已经在ApplicationContext中包含了该bean,但是通过new运算符创建的对象将不会被Spring处理(注释将不起作用).

What happen if you create your bean with @Autowired dependencies via new operator? Nothing, because it isn't actually a bean. The object you created isn't related to IoC container. You may have the bean already in your ApplicationContext if you marked it with @Component(for example) but the object which was created via new operator wont be processed by Spring(annotations won't work).

希望这会有所帮助.

PS:生命周期得到简化.

PS: The lifecycle is simplified.

这篇关于自动装配在springboot应用程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆