【问题标题】:Which is the Spring equivalent for the CDI @Produces annotation?哪个是 CDI @Produces 注释的 Spring 等效项?
【发布时间】:2014-11-10 15:40:58
【问题描述】:

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

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

【问题讨论】:

    标签: java spring dependency-injection cdi


    【解决方案1】:

    你正在寻找@Bean:

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

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

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

    我建议您阅读以下内容:Spring DI and CDI comparative study

    【讨论】:

    • 当心一个主要区别 - CDI 生产者可以访问 InjectionPoint,这允许它执行一些额外的技巧。
    • 你也可以使用@Autowired来传递需要注入到bean中的元素并设置它们。
    • 使用 CDI 可以注入非 bean 本身的原始类型或对象。这对 Spring 也有效吗?同样,当我做对时,概念是不同的:虽然 CDI 允许每个 bean 生成一个可注入对象,但在 Spring 中,只有使用 @Configuration 注释的类可以生成 Bean(否则在 Lite 模式下)。意图不同...
    • @Wecherowski Spring 允许您使用 @Value 注入原始类型。
    猜你喜欢
    • 2020-05-15
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多