Spring Dependency Injection无法正常工作

时间:2018-05-09 10:37:24

标签: java spring dependency-injection

我有一个Spring / Swing应用程序,其中我正在试验DI但是到目前为止我做了什么,我无法使其正常工作。以下是我工作的一些示例类;

public class Launcher {

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                ApplicationContext context = null;
                try {
                    context = new AnnotationConfigApplicationContext(AppConfig.class);
                    MainFrame mainFrame = (MainFrame) context.getBean("mainFrame");
                    mainFrame.init();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (context != null)
                        ((ConfigurableApplicationContext) context).close();
                }
            }
        });

    }

}


@Configuration
@ComponentScan("tr.com.example.*")
public class AppConfig {

    @Bean(name = "mainFrame")
    public MainFrame createMainFrame() {
        return new MainFrame();
    }
}


public class MyPanel{

    @Autowired
    MyManager manager;

    ...do stuff
}


@Service
public class MyManager{
    ...do stuff
}

因此,当我尝试将MyManager注入MyPanel时,我得到了NullPointerException。但是如果我尝试将它注入MainFrame就可以了。

有人可以向我解释一下这里有什么问题吗?我应该如何正确地做到这一点?

提前致谢。

2 个答案:

答案 0 :(得分:2)

您的MyPanel不是@Component,因此Spring无法看到,任何@Autowired或其他注释都无法处理。

Spring的关键是完全使用它。除非你知道某些东西不应该是一个bean(即域类,实体等),否则它可能应该是一个bean。

答案 1 :(得分:0)

由于你没有在MyPanel上使用@Component

,因此无法正常工作
public class Launcher {

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                ApplicationContext context = null;
                try {
                    context = new AnnotationConfigApplicationContext(AppConfig.class);
                    MainFrame mainFrame = (MainFrame) context.getBean("mainFrame");
                    mainFrame.init();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (context != null)
                        ((ConfigurableApplicationContext) context).close();
                }
            }
        });

    }

}


@Configuration
@ComponentScan("tr.com.example.*")
public class AppConfig {

    @Bean(name = "mainFrame")
    public MainFrame createMainFrame() {
        return new MainFrame();
    }
}

@Component
public class MyPanel{

    @Autowired
    MyManager manager;

    ...do stuff
}


@Service
public class MyManager{
    ...do stuff
}