SWT and Spring's @Configurable - Dependency Injection for the UI - codecentric AG Blog

:

Given the following technology stack:

– Java frontend with the Standard Web Toolkit (SWT), started via Java Web Start.
– Spring Remoting as the interface to the backend.
– Spring web application on a Tomcat as backend.

The backend is standard Spring, and who doesn’t know what Spring Remoting is can read it up here. Here I wanna talk about the combination of Spring and SWT in the frontend.

So, what are the goals? We want the UI components to be as dumb as possible, because they are a little harder to test. Everything that smells like business logic should be located in easy-to-test-POJOs. Components should be wired up via dependency injection, removing the need for service locators in the code.

I had no experience with SWT, so my first naive thought was, good, SWT UI components are becoming Spring beans, services on the client side are Spring Remoting proxies, and between the services and the UI components we add a layer of controllers containing any business logic.

It wasn’t that easy.

SWT UI components have their own lifecycle, they may be created and disposed at any time, and recreated again. The scope Singleton would definitely have been the wrong one. Okay, I thought, then the UI components would be prototype beans, and whenever we need one, we create it.

Even that’s easier said than done. Let’s take a look at a typical UI Component.

public class SomeListView extends Composite
{
	private TabFolder tabFolder;
	private SomeFilterComponent someFilterComponent;
	private SomeSortableGrid grid;
 
	public SomeListView(Composite parent)
	{
		super(parent, SWT.EMBEDDED);
		setLayout(new GridLayout(1, false));
		someFilterComponent = new SomeFilterComponent(this, SWT.NONE);
		someFilterComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
 
		tabFolder = new TabFolder(this, SWT.NONE);
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
 
		TabItem someListTab = new TabItem(tabFolder, SWT.NONE);
		someListTab.setText("some list");
 
		grid = new SomeSortableGrid(tabFolder, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		grid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		grid.setHeaderVisible(true);
		grid.setSize(this.getSize().x, 400);
		grid.setAutoHeight(true);
		grid.setAutoWidth(true);
 
		campaignListTab.setControl(grid);
	}
}

public class SomeListView extends Composite { private TabFolder tabFolder; private SomeFilterComponent someFilterComponent; private SomeSortableGrid grid;public SomeListView(Composite parent) { super(parent, SWT.EMBEDDED); setLayout(new GridLayout(1, false)); someFilterComponent = new SomeFilterComponent(this, SWT.NONE); someFilterComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));tabFolder = new TabFolder(this, SWT.NONE); tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));TabItem someListTab = new TabItem(tabFolder, SWT.NONE); someListTab.setText("some list");grid = new SomeSortableGrid(tabFolder, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); grid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); grid.setHeaderVisible(true); grid.setSize(this.getSize().x, 400); grid.setAutoHeight(true); grid.setAutoWidth(true);campaignListTab.setControl(grid); } }

This component is a view with a list that can be filtered via a filter component. The list is displayed in a tab. SomeFilterComponent and SomeSortableGrid are proprietary UI components as well. As you can see, the parent component is always a constructor argument to the child component. We have a bidirectional dependency here that makes dependency injection hard: if you want to inject SomeFilterComponent into SomeListView, you would have to create SomeListView before, so that it can be used in the constructor of SomeFilterComponent. That would still be possible with Singletons, but taking into account that both components need to be Prototypes it gets impossible.

Conclusion: SWT – UI components cannot become Spring beans.

What now? Good old service locators again?

No, there is an elegant solution with a little bit of AspectJ magic needing very little effort. Here the three steps involved:


1. Include the Maven-AspectJ-Plugin for compile-time-weaving in our pom
2. Use @Configurable and @Autowired in our UI component classes
3. Activate dependency injection in the application-context.xml

This way we can inject Spring beans in normal objects (our UI components) created via normal constructor invocation.

Let’s go into the details:

1. Include the Maven-AspectJ-Plugin for compile-time-weaving in our pom

<build>
	<plugins>
		<plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>aspectj-maven-plugin</artifactId>
			<version>1.4</version>
			<configuration>
				<source>1.6</source>
				<target>1.6</target>
				<complianceLevel>1.6</complianceLevel>
				<Xlint>ignore</Xlint>
				<aspectLibraries>
					<aspectLibrary>
						<groupId>org.springframework</groupId>
						<artifactId>spring-aspects</artifactId>
					</aspectLibrary>
				</aspectLibraries>
			</configuration>
			<executions>
				<execution>
					<goals>
						<goal>compile</goal>
						<goal>test-compile</goal>
					</goals>
				</execution>
			</executions>
			<dependencies>
				<dependency>
					<groupId>org.aspectj</groupId>
					<artifactId>aspectjrt</artifactId>
					<version>1.6.11</version>
				</dependency>
				<dependency>
					<groupId>org.aspectj</groupId>
					<artifactId>aspectjtools</artifactId>
					<version>1.6.11</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

Having this configuration included in the pom the aspects from spring-aspects will be woven into the classes. We are interested in the AnnotationBeanConfigurerAspect, that will be woven into each class annotated with @Configurable. Now we can use the @Autowired annotation to inject dependencies in those classes, which leads us directly to the next point.

2. Use @Configurable and @Autowired in our UI component classes

@Configurable(preConstruction = true)
public class SomeListView extends Composite
{
	private TabFolder tabFolder;
	private SomeFilterComponent someFilterComponent;
	private SomeSortableGrid grid;
	@Autowired
	private SomeController someController;
 
	public SomeListView(Composite parent)
	{
		super(parent, SWT.EMBEDDED);
		setLayout(new GridLayout(1, false));
		someFilterComponent = new SomeFilterComponent(this, SWT.NONE);
		someFilterComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
 
		tabFolder = new TabFolder(this, SWT.NONE);
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
 
		TabItem someListTab = new TabItem(tabFolder, SWT.NONE);
		someListTab.setText("some list");
 
		grid = new SomeSortableGrid(tabFolder, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		grid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		grid.setHeaderVisible(true);
		grid.setSize(this.getSize().x, 400);
		grid.setAutoHeight(true);
		grid.setAutoWidth(true);
 
		campaignListTab.setControl(grid);
		someController.doSomething();
	}
}

@Configurable(preConstruction = true) public class SomeListView extends Composite { private TabFolder tabFolder; private SomeFilterComponent someFilterComponent; private SomeSortableGrid grid; @Autowired private SomeController someController;public SomeListView(Composite parent) { super(parent, SWT.EMBEDDED); setLayout(new GridLayout(1, false)); someFilterComponent = new SomeFilterComponent(this, SWT.NONE); someFilterComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));tabFolder = new TabFolder(this, SWT.NONE); tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));TabItem someListTab = new TabItem(tabFolder, SWT.NONE); someListTab.setText("some list");grid = new SomeSortableGrid(tabFolder, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); grid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); grid.setHeaderVisible(true); grid.setSize(this.getSize().x, 400); grid.setAutoHeight(true); grid.setAutoWidth(true);campaignListTab.setControl(grid); someController.doSomething(); } }

@Configurable is telling AspectJ to weave the AnnotationBeanConfigurerAspect into those classes. When you set ‘preConstruction = true’ as an annotation parameter, dependencies will even be injected before the constructor of the class is called. That’s why we can use SomeController in the constructor here. Dependencies you want to inject have to be annotated with @Autowired, like it is done here with the SomeController.

3. Activate dependency injection in the application-context.xml

The AnnotationBeanConfigurerAspect being woven in doesn’t mean that it can get active right away. Aspects are static usually, so we have to expose our ApplicationContext in a static place the aspect knows. Spring is doing this transparently when we add the following to the ApplicationContext xml file:

<context:spring-configured/>

For activating the autowiring via annotations we need the following entry:

<context:annotation-config/>

That’s it. Now we can create SomeListView via constructor and the dependencies get injected automatically. No service locator, no glue code. Everything smelling like business logic can be sourced out into controllers (or however you wanna name them) being injected into the UI component. The UI component itself stays as simple as possible.

One additional word regarding testability

If you take a look again at the code of SomeListView, you’ll notice a Nullpointer being thrown whenever you instantiate the class without having an application context configured in the right way. We accepted that you cannot test SWT – UI components easily in a standard unit test (that’s nothing about Spring – since the UI components are coupled tightly through the constructor calls, unit testing is impossible (to be clear: I’m talking about unit tests, not JUnit tests)). For testing an UI component we use the following base class:

@ContextConfiguration("classpath:conf/some-config-test.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public abstract class AbstractViewTest
{
	protected Shell shell;
 
	@Autowired
	protected SomeController someControllerMock;
 
	@Before
	public void setUp() throws Exception
	{
		assertNotNull(someControllerMock);
 
		shell = new Shell(Display.getDefault(), SWT.NONE);
	}
}

@ContextConfiguration("classpath:conf/some-config-test.xml") @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext public abstract class AbstractViewTest { protected Shell shell;@Autowired protected SomeController someControllerMock;@Before public void setUp() throws Exception { assertNotNull(someControllerMock);shell = new Shell(Display.getDefault(), SWT.NONE); } }

some-config-test.xml looks like this:

<bean class="org.mockito.Mockito" factory-method="mock" >
	<constructor-arg value="de.codecentric.client.controller.SomeController"/>
</bean>

<context:annotation-config/>
<context:spring-configured/>

A test class for SomeListView could look like this:

public class SomeListViewTest extends AbstractViewTest
{
	private SomeListView someListView;
 
	@Before
	public void setUp() throws Exception
	{
		super.setUp();
		SomeObject something = new SomeObject();
 
		when(someControllerMock.doSomething()).thenReturn(something);
		someListView = new SomeListView(shell);
	}
 
	@Test
	public void testSomeListView()
	{
		Control[] children = someListView.getChildren();
		assertEquals(2, children.length);
 
		assertTrue(children[0] instanceof SomeFilterComponent);
		assertTrue(children[1] instanceof TabFolder);
 
		TabFolder tabFolder = (TabFolder) children[1];
		Control[] tabFolderChildren = tabFolder.getChildren();
		assertEquals(1, tabFolderChildren.length);
		assertTrue(tabFolderChildren[0] instanceof SomeSortableGrid);
 
	}
}

public class SomeListViewTest extends AbstractViewTest { private SomeListView someListView;@Before public void setUp() throws Exception { super.setUp(); SomeObject something = new SomeObject();when(someControllerMock.doSomething()).thenReturn(something); someListView = new SomeListView(shell); }@Test public void testSomeListView() { Control[] children = someListView.getChildren(); assertEquals(2, children.length);assertTrue(children[0] instanceof SomeFilterComponent); assertTrue(children[1] instanceof TabFolder);TabFolder tabFolder = (TabFolder) children[1]; Control[] tabFolderChildren = tabFolder.getChildren(); assertEquals(1, tabFolderChildren.length); assertTrue(tabFolderChildren[0] instanceof SomeSortableGrid);} }

The someControllerMock gets injected into someListView automatically, when someListView is created via constructor call. All necessary validations can be done on the mock.