Micronaut - 什么是 Springframework @Bean 等价物?

Micronaut - What is Springframework @Bean equivalent?

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

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 引导,可以添加 @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

The @Prototype annotation is a synonym for @Bean because the default scope is 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();
    }
}