I have a class, being injected by guice and this class constructor invokes super, with resource loaded by class.getResource(..)
@SuppressWarnings("serial")
public class CleanAction extends AbstractAction {
private final JTable table;
private final PowderTableModel tableModel;
@Inject
public CleanAction(@Named("data") JTable table, PowderTableModel tableModel) {
super("Clean", new ImageIcon(CleanAction.class.getResource("/icons/table.png")));
this.table = table;
this.tableModel = tableModel;
}
...
}
It works fine in tests, but during guice initialization the result of CleanAction.cl开发者_StackOverflow中文版ass.getResource("icons/table.png") is null, so it fails with NullPointerException.
Is there any guice way to inject resources?
To answer your question "Is there any guice way to inject resources?", I would say "no, not out of the box".
However, I have implemented one ResourceInjector
service, based on Guice, in Guts-GUI framework (Apache License 2.0). Feel free to take a look at it and see how I have used Guice features to ensure that resources can be injected at Guice injection time.
This is much more general than what you describe (in "resources" I include text for JLabel
, JButton
...)
Please note, however, that automatic resource injection is a complex business (many different types of resources...)
Why do you need guice to inject resources? Looks like your file is not in classpath during normal work. It is in classpath only during tests. Try to add it to classpath also when you are running it normally, not for tests.
Are you using maven? Maybe you have your file in src/test/resources
, while it should be in src/main/resources
?
精彩评论