Micronaut-什么是Springframework@Bean等价物



我是Micronauts的新手,在开发春季启动应用程序方面有相当多的经验。在这种背景下,我无意中创建了自定义bean,就像我过去在Spring应用程序上使用@Bean注释创建的那样。在我的例子中,我有一个库,它提供了一个接口及其实现类。我想在我的代码中使用接口,并尝试注入实现,但它失败了,出现以下错误

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).

这是我的代码

@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);
}
}

我确信我在做一些错误的事情,需要了解该怎么做。我通过添加下面的代码和删除metaDataParser周围的注释来完成这项工作。

@PostConstruct
public void initialize() {
//Want to Avoid This stuff
this.metaDataParser = new MetaDataParserImpl();
}

使用Spring Boot,可以添加@Bean注释来创建一些自定义bean,我们可以使用@Autowired在应用程序的任何地方注入它。在Micronauths上,有没有我缺少的类似产品。我浏览了上的指南https://docs.micronaut.io/2.0.0.M3/guide/index.html但没能得到任何东西来让它发挥作用。

有人能建议我如何使用@Inject注入自定义bean吗?

如果你想看到这一点,这里是Github上的应用程序。https://github.com/reflexdemon/saml-metadata-viewer

Deadpool的帮助和一些阅读的帮助下,我得到了我想要的东西。解决方案是创建@BeanFactory

请参阅此处的Javadoc:https://docs.micronaut.io/latest/guide/ioc.html#builtInScopes

@Prototype注释是@Bean的同义词,因为默认作用域是prototype。

因此,这里有一个与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();
}
}

最新更新