Reputation: 419
I have a Spring/Swing application in which I'm experimenting DI but whatever I've done so far, I couldn't make it work properly. Here are some example classes I work on;
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
}
So, when I try to inject MyManager to MyPanel, I'm getting NullPointerException. But if I try to inject it to MainFrame it works.
Can someone please explain me what's wrong here and how should I make it correctly?
Thanks in advance.
Upvotes: 0
Views: 353
Reputation: 97
It is not working beacuse you have not use @Component over MyPanel
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
}
Upvotes: 0
Reputation: 73528
Your MyPanel
is not a @Component
, therefore it's invisible to Spring and any @Autowired
or other annotations won't be processed.
The key to Spring is to use it fully. Unless you know that something shouldn't be a bean (i.e. a domain class, entity or so on) it probably should be a bean.
Upvotes: 2