Permalink
Browse files

Multiple implementations injection.

  • Loading branch information...
1 parent 129af0c commit f86ac8490ef7b8ef013e62c841f839a07251a504 @jponge committed Apr 2, 2012
View
@@ -191,7 +191,7 @@
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="VcsDirectoryMappings">
- <mapping directory="" vcs="" />
+ <mapping directory="" vcs="Git" />
</component>
<component name="libraryTable">
<library name="Maven: aopalliance:aopalliance:1.0">
@@ -1,28 +1,37 @@
package my.app;
import my.app.hello.Greeter;
+import my.app.multiple.NumberGenerator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
+import java.util.Set;
@Named
@Singleton
public class Main {
private final Greeter greeter;
+ private final Set<NumberGenerator> generators;
@Inject
- public Main(Greeter greeter) {
+ public Main(Greeter greeter, Set<NumberGenerator> generators) {
this.greeter = greeter;
+ this.generators = generators;
}
-
+
public void run() {
System.out.println(greeter.greet("Mr Bean"));
+ for (int i = 0; i < 10; i++) {
+ for (NumberGenerator generator : generators) {
+ System.out.println(generator.next());
+ }
+ }
}
-
+
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/main.xml");
Main app = context.getBean(Main.class);
@@ -0,0 +1,6 @@
+package my.app.multiple;
+
+public interface NumberGenerator {
+
+ public int next();
+}
@@ -0,0 +1,14 @@
+package my.app.multiple;
+
+import javax.inject.Named;
+import java.util.Random;
+
+@Named
+public class RandomNumberGenerator implements NumberGenerator {
+
+ private final Random random = new Random();
+
+ public int next() {
+ return random.nextInt();
+ }
+}
@@ -0,0 +1,13 @@
+package my.app.multiple;
+
+import javax.inject.Named;
+
+@Named
+public class SequenceNumberGenerator implements NumberGenerator {
+
+ private int value = 0;
+
+ public int next() {
+ return value++;
+ }
+}

0 comments on commit f86ac84

Please sign in to comment.