Assisted injection support #8461
-
Hi, I'm trying to convert a project that uses dagger 2 to micronaut. One thing the dagger supports is assisted injection (another injection framework that supports assisted injection is Guice). Does micronaut support this? This is the example that I am trying to convert. import dagger.assisted.Assisted;
import dagger.assisted.AssistedFactory;
import dagger.assisted.AssistedInject;
public class DialogBox {
private final Messages messages;
@AssistedInject
DialogBox(Messages messages, @Assisted String caption) {
this.messages = messages;
messages.log(String.format("creating DialogBox(%s)", caption));
}
public void show() {
messages.log("show dialog");
}
@AssistedFactory
public interface Factory {
DialogBox create(String caption);
}
} public class App {
private final DialogBox.Factory dialogBoxFactory;
@Inject
App(DialogBox.Factory dialogBoxFactory) {
this.dialogBoxFactory = dialogBoxFactory;
}
public void run() {
DialogBox dlg1 = dialogBoxFactory.create("dlg1");
DialogBox dlg2 = dialogBoxFactory.create("dlg2");
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
graemerocher
Dec 5, 2022
Replies: 2 comments 1 reply
-
closest thing here is parameterized beans: import jakarta.inject.*;
import io.micronaut.context.annotation.*;
@Singleton
public class DialogBox {
private final Messages messages;
@Inject
DialogBox(Messages messages, @Parameter String caption) {
this.messages = messages;
messages.log(String.format("creating DialogBox(%s)", caption));
}
public void show() {
messages.log("show dialog");
}
public interface Factory {
DialogBox create(String caption);
}
@Singleton
class FactoryImpl implements Factory {
private final BeanContext context;
FactoryImpl(BeanContext context) {
this.context = context;
}
@Override
public DialogBox create(String caption) {
context.createBean(DialogBox.class, caption);
}
}
} If you don't want to implement the factory you could write introduction advice that implements it for you: @Introduction
@Retention(RUNTIME)
public @interface Assisted {
}
@Assisted
public interface Factory {
DialogBox create(String caption);
}
@InterceptorBean(Assisted.class)
class AssistedInterceptor implements MethodInterceptor<Object, Object> {
private final BeanContext context;
AssistedInterceptor(BeanContext context) {
this.context = context;
}
@Override
public Object intercept(InvocationContext context) {
var beanType = context.getReturnType().getType();
return context.createBean(beanType, context.getParameterValues());
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
graemerocher
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
closest thing here is parameterized beans: