java 哪个是 CDI @Produces 注释的 Spring 等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25876402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:50:08  来源:igfitidea点击:

Which is the Spring equivalent for the CDI @Produces annotation?

javaspringdependency-injectioncdi

提问by Renato Dinhani

When I was working with CDI, I could use the @Producesannotation to create a producer method to be called to choose which bean that implemented an interface would be injected by the @Injectannotation .

当我使用 CDI 时,我可以使用@Produces注解创建一个生产者方法来调用来选择哪个实现了接口的 bean 将被@Inject注解注入。

Now I am working with Spring, but I didn't find anything similar. What I need to use to achieve the same result I had with the @Producesannotation in CDI when I use the @Autowiredannotation?

现在我正在使用 Spring,但我没有发现任何类似的东西。@Produces当我使用@Autowired注释时,我需要使用什么来实现与CDI 中的注释相同的结果?

回答by Luiggi Mendoza

You're looking for @Bean:

您正在寻找@Bean

@Bean is a method-level annotation and a direct analog of the XML <bean/>element. The annotation supports most of the attributes offered by <bean/>, such as: init-method, destroy-method, autowiring, lazy-init, dependency-check, depends-on and scope.

@Bean 是一个方法级的注解,是 XML<bean/>元素的直接模拟。该注解支持 提供的大部分属性<bean/>,例如:init-method、destroy-method、autowiring、lazy-init、dependency-check、depends-on 和 scope。

Example (taken from link above):

示例(取自上面的链接):

@Configuration
public class AppConfig {
    //similar to @Produces CDI annotation
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

I suggest you to pay a read to this: Spring DI and CDI comparative study

我建议您阅读一下:Spring DI 和 CDI 比较研究