如何获得JSR-330带注释的外部类的注入实例

时间:2019-07-15 14:17:29

标签: micronaut

当我将Micronauts的编译时依赖注入限制在我自己的本地项目的类中时,效果很好。

但是,如果注入的实例驻留在外部依赖项中(例如handy-external-library.jar),则会失败...

外部jar的类(例如“ LdapConnector”)确实具有适当的类级别JSR-330 javax.inject.Singleton注释集。

请注意,我无法控制外部jar,因此无法直接修改其源代码或pom.xml

似乎是一个相关问题:https://github.com/micronaut-projects/micronaut-core/issues/1101

我试图:

  1. 将外部依赖项添加到maven-compiler-plugin中,认为这可能会使handy-external-library.jar成为注释处理器类路径的一部分

  2. 绕开内省注释,认为它可能隐式注册注释元数据

但是只要我使用:

@Inject
private LdapConnector ldapConnector;

结果为:

io.micronaut.context.exceptions.BeanInstantiationException: Bean definition [cool.api.HelloWorldController] could not be loaded: Failed to inject value for field [ldapConnector] of class: cool.api.HelloWorldController.
Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).

一些细节:

mn --version
| Micronaut Version: 1.1.2
| JVM Version: 1.8.0_171

mn create-app cool-api --build=maven --features=spock

mn
| Starting interactive mode...
| Enter a command name to run. Use TAB for completion:
mn> create-controller HelloWorld
mn> exit

1 个答案:

答案 0 :(得分:0)

为外部类创建bean是@Factory功能的作用。

@Factory
class LdapFactory {

    @Singleton
    LdapConnector connector() {
        ... return an instance of LdapConnector
    }
}

请参见https://docs.micronaut.io/latest/guide/index.html#factories