ref*_*mon 4 java spring inversion-of-control micronaut
我对 Micronauts 非常陌生,并且在开发 Spring Boot 应用程序方面有相当多的经验。有了这个背景,我偶然发现了创建自定义 bean,就像我过去@Bean在 Spring 应用程序上使用注释创建的方式一样。就我而言,我有一个提供接口及其实现类的库。我想在代码中使用该接口并尝试注入实现,但失败并出现以下错误
Caused by: io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [io.vpv.saml.metadata.service.MetaDataParser] exists for the given qualifier: @Named('MetaDataParserImpl'). 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).
Run Code Online (Sandbox Code Playgroud)
这是我的代码
Caused by: io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [io.vpv.saml.metadata.service.MetaDataParser] exists for the given qualifier: @Named('MetaDataParserImpl'). 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).
Run Code Online (Sandbox Code Playgroud)
我确信我做错了什么,需要了解该怎么做。我通过添加以下代码并删除周围的注释来完成此工作metaDataParser。
@Singleton
public class ParseMetadataImpl implements ParseMetadata {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Inject
@Named("MetaDataParserImpl")
private MetaDataParser metaDataParser;
@Override
public IDPMetaData getIDPMetaData(URL url) throws IOException {
logger.info("Parsing {}", url);
logger.info("metaDataParser {}", metaDataParser);
return metaDataParser.parseIDPMetaData(url);
}
}
Run Code Online (Sandbox Code Playgroud)
使用 Spring Boot 可以添加@Bean注释来创建一些自定义 bean,我们可以将@Autowired其注入到应用程序的任何位置。Micronauts 上是否有我缺少的同等内容。我浏览了https://docs.micronaut.io/2.0.0.M3/guide/index.html上的指南,但无法获得任何信息来使其正常工作。
有人可以建议我如何使用 @Inject 来注入自定义 bean 吗?
如果你想看这个,这里是 Github 上的应用程序。 https://github.com/reflexdemon/saml-metadata-viewer
ref*_*mon 11
在帮助Deadpool和一些阅读的帮助下,我得到了我想要的东西。解决方案正在创建@BeanFactory
请参阅此处的 Javadoc:https ://docs.micronaut.io/latest/guide/ioc.html#builtInScopes
注释
@Prototype是同义词,@Bean因为默认范围是原型。
因此,这里是一个与 Spring 框架的行为相匹配的示例
对于任何也在寻找此类东西的人来说,这都是答案。
import io.micronaut.context.annotation.Factory;
import io.vpv.saml.metadata.service.MetaDataParser;
import io.vpv.saml.metadata.service.MetaDataParserImpl;
import javax.inject.Singleton;
@Factory
public class BeanFactory {
@Singleton
public MetaDataParser getMetaDataParser() {
return new MetaDataParserImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6630 次 |
| 最近记录: |