Skip to content

Instantly share code, notes, and snippets.

@royling
Forked from cbeams/MapInjectionTests.java
Created May 30, 2019 08:03
Show Gist options
  • Save royling/de2a09f1b89dd8c90d8b0057618654a1 to your computer and use it in GitHub Desktop.
Save royling/de2a09f1b89dd8c90d8b0057618654a1 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