[英]Spring Dependency Injection not working correctly
我有一個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,則可以正常工作。
有人可以解釋一下這是怎么回事,我應該如何正確解決?
提前致謝。
您的MyPanel
不是@Component
,因此對於Spring來說是不可見的,任何@Autowired
或其他注釋都不會被處理。
Spring的關鍵是充分利用它。 除非您知道某些東西不應該是Bean(即域類,實體等),否則可能應該是Bean。
由於您沒有在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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.