views:

62

answers:

2

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.class.getResource("icons/table.png") is null, so it fails with NullPointerException.

Is there any guice way to inject resources?

+1  A: 

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?

amorfis
It is in src/main/resources
Shaman
So I assume there must be something in the way you are running it. Looks like `src/main/resources` is not included in classpath then. How are you running it? Are you building .jar by maven, and then running this .jar?
amorfis
yes. The problem was solved in a strange way -- I've removed all subfolders in resources and just ask for resource named, for instance "image.png"
Shaman
+1  A: 

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...)

jfpoilpret
Thanks for a good guts project, it seems to be fine.
Shaman