为什么@autowired doos不能实现我的领域?

时间:2015-07-29 15:29:13

标签: spring swing autowired

我使用的是Spring启动注释样式,经过多次搜索后我不明白,为什么带注释的字段会返回null。

请低于我的java代码:

package app.ui;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyFrame extends JFrame {
  private JMenu     fileMenu;
  private JMenuBar  menuBar;
  private JMenuItem openMenuItem;

  @Autowired
  MyDialog myDialog;

  @Autowired
  JdbcTemplate jdbcTemplate;


  public MyFrame() {
    initComponents();
    setVisible(true);
  }


  private void initComponents() {
    jdbcTemplate.toString();
    this.setTitle("Vue de ma fenêtre");
    this.setSize(new Dimension(300, 150));
    this.setLocationRelativeTo(null);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    this.getContentPane().setLayout(new FlowLayout());

    menuBar = new JMenuBar();
    fileMenu = new JMenu();
    openMenuItem = new JMenuItem();
    fileMenu.setText("File");
    openMenuItem.setText("Inscription");
    openMenuItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        myDialog.setVisible(true);
      }
    });
    fileMenu.add(openMenuItem);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);
    //
    final JButton cmd1 = new JButton("Créer Table");
    getContentPane().add(cmd1);
    cmd1.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
        jdbcTemplate.execute(
            "CREATE TABLE customer(id bigint(11), nom VARCHAR(55), prenom VARCHAR(55), dnaiss date)");
        cmd1.setEnabled(false);
      }
    });

    //

在此示例中,jdbcTemplate.toString()返回null,我无法理解原因,因为它在下面的操作中执行Performed方法

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是Java初始化类的方式,第一个构造函数后来执行的类变量被初始化。直到并且除非变量是静态块的一部分。同样的逻辑后面跟着spring。

在您的示例中,jdbcTemplate是一个类变量,jdbcTemplate.toString();通过默认构造函数调用,而在MyFrame实例上调用actionperformed。

要了解有关类初始化的更多信息,请查看以下链接

http://www.javaworld.com/article/2075796/java-platform/java-101--class-and-object-initialization.html?nsdr=true