Skip to content

Commit

Permalink
Add a test that uses `Supplier<T> wrt #519 (#521)
Browse files Browse the repository at this point in the history
Note that with `Supplier<T>` its a little different than `Provider<T>` in that `Provider<T>` is used to support circular dependency wiring so its a way to delay the wiring (until after all the constructors are called).

We don't have that limitation with Supplier.
  • Loading branch information
rbygrave authored Mar 12, 2024
1 parent cf59263 commit f79353e
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.example.myapp.supplier;

import io.avaje.inject.Component;

import java.util.function.Supplier;

@Component
class MySupConsumer {

private final Supplier<MySupFactory.SupFoo> supplier;
private MySupFactory.SupFoo supFoo;

MySupConsumer(Supplier<MySupFactory.SupFoo> supplier) {
this.supplier = supplier;
supFoo = supplier.get();
}

MySupFactory.SupFoo current() {
return supFoo;
}

MySupFactory.SupFoo next() {
supFoo = supplier.get();
return supFoo;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.example.myapp.supplier;

import io.avaje.inject.Bean;
import io.avaje.inject.Factory;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

@Factory
public final class MySupFactory {

private final AtomicInteger counter = new AtomicInteger();

@Bean
Supplier<SupFoo> supplyIt() {
return () -> new SupFoo(counter.incrementAndGet());
}

public static class SupFoo {

private final int id;

SupFoo(int id) {
this.id = id;
}

public int id() {
return id;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.example.myapp.supplier;

import io.avaje.inject.BeanScope;
import org.example.external.aspect.sub.ExampleExternalAspectModule;
import org.example.myapp.MyappModule;
import org.junit.jupiter.api.Test;
import org.other.one.OneModule;

import static org.assertj.core.api.Assertions.assertThat;

class MySupFactoryTest {

@Test
void supplierOfFoo() {
try (var beanScope = BeanScope.builder()
.modules(new ExampleExternalAspectModule(), new OneModule(), new MyappModule())
.build()) {

MySupConsumer supConsumer = beanScope.get(MySupConsumer.class);
MySupFactory.SupFoo current = supConsumer.current();
assertThat(current.id()).isEqualTo(1);

MySupFactory.SupFoo next = supConsumer.next();
assertThat(next.id()).isEqualTo(2);

MySupFactory.SupFoo next2 = supConsumer.next();
assertThat(next2.id()).isEqualTo(3);
}

}
}

0 comments on commit f79353e

Please sign in to comment.