Skip to content

Instantly share code, notes, and snippets.

@cbeams
Created February 2, 2012 10:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cbeams/1722754 to your computer and use it in GitHub Desktop.
Save cbeams/1722754 to your computer and use it in GitHub Desktop.
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acme;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
public class MapInjectionTests {
@Test
public void test() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
Foo foo = ctx.getBean(Foo.class);
assertThat(foo.getPlugins().length, is(2));
assertThat(foo.getPlugins()[0], instanceOf(PluginB.class));
assertThat(foo.getPlugins()[1], instanceOf(PluginA.class));
}
}
@Configuration
@ComponentScan(basePackageClasses=Config.class)
class Config {
@Autowired Map<String, Plugin> plugins;
@Bean
public Foo foo() {
Foo foo = new Foo();
foo.addPlugin(plugins.get("pluginB"));
foo.addPlugin(plugins.get("pluginA"));
return foo;
}
}
interface Plugin { }
@Component class PluginA implements Plugin { }
@Component class PluginB implements Plugin { }
class Foo {
private Set<Plugin> plugins = new LinkedHashSet<Plugin>();
public void addPlugin(Plugin plugin) {
this.plugins.add(plugin);
}
public Plugin[] getPlugins() {
return this.plugins.toArray(new Plugin[this.plugins.size()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment