Friday, 6 March 2009

Using Fuse for Dependency Injection in Swing

The fuse project for dependency injection can be found at https://fuse.dev.java.net.

The overview is quite simple and can be found at https://fuse.dev.java.net/gettingstarted.html.

in short, Fuse uses a text file containing resources and values to be injected into the object at run time.

The following code shows a very simple example of how to use fuse:

1: Create the Resource File

create the package test and create the file testfuse.resources in that package.

add the following line to testfuse.resources

TestFuse.name=Jon Doe

When this resource file is applied by fuse, it will inject the value Jon Doe into the member name in the class TestFuse

2: Create the Java code to inject the resources

Create the class TestFuse.java to read the resource file and use fuse to inject the contents.

package test;
import org.jdesktop.fuse.InjectedResource;
import org.jdesktop.fuse.ResourceInjector;

public class TestFuse
{
@InjectedResource
private String name;

public String toString()
{
return this.getClass().getName()+"[name="+name+"]";
}

public static void main(String[] args)
{
ResourceInjector.get().load(TestFuse.class.getResource("testfuse.resources"));

TestFuse testFuse = new TestFuse();
ResourceInjector.get().inject(testFuse);

System.out.println(testFuse);
}
}

No comments:

Post a Comment