如何在spring boot中使用@Bean为抽象类创建bean [英] How to create bean using @Bean in spring boot for abstract class

查看:1595
本文介绍了如何在spring boot中使用@Bean为抽象类创建bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求将旧式spring项目迁移到Spring引导。
假设下面的代码片段我必须迁移到Spring引导样式。

I have requirement to migrate old style spring project to Spring boot. Assume below code snippet I have to migrate to Spring boot style.

这里我问一下,如何将下面的abstract bean转换为@Bean?

Here my ask , how to convert below abstract bean to @Bean ?

<bean id="sample" class="com.test.core.common.AbstractClass" abstract="true">
    <property name="sample1" ref="sample1" />
     <property name="sample2" ref="sample2" />
</bean>


推荐答案

用普通Java编写你的抽象基类(没有任何Spring耦合):

Write your abstract base class in plain Java (without any Spring coupling) :

public abstract class AbstractClass{   
    private Sample1 sample1;
    private Sample2 sample2;

    public AbstractClass(Sample1 sample1, Sample1 sample2){
       this.sample1 = sample1;
       this.sample2 = sample2;
   }
   ... 
}

请注意添加带参数的构造函数(包括抽象类和具体类)使注入更容易,依赖性更清晰。

Note that adding a constructor with parameters (both for the abstract class and the concrete class) makes injection easier and dependencies clearer.

那么你有两种方法:

1)使用 @Component 注释具体类。

例如:

1) Annotate the concrete class(es) with @Component.
Such as :

@Component
public class MyClass extends AbstractClass{   
    public MyClass (Sample1 sample1, Sample1 sample2){
        super(sample1, sample2);
    }
}

第一种方式有优势:要添加的注释。

但它实际上将子类作为可能由Spring上下文加载的bean。

This first way has the advantage to be short : just an annotation to add.
But it makes de facto the subclass as a bean that may potentially be loaded by the Spring context.

2)或者,在 Configuration 类中声明bean。

例如:

2) Alternatively, declare the bean in a Configuration class.
Such as :

@Configuration
public class MyConfig{
  @Bean
   public MyClass myClass(Sample1 sample1, Sample1 sample2){
      return new MyClass(sample1, sample1);
   }
}

第二种方式更详细但有优势不修改子类代码,也让类的客户端决定该类是否应该是bean。

This second way is more verbose but has the advantage to not modify the subclass code and also let clients of the class to decide whether the class should be a bean.

每种方法都有其优点和缺点。

根据具体要求使用。

Each approach has its advantages and its drawbacks.
So to use according to the concrete requirement.

这篇关于如何在spring boot中使用@Bean为抽象类创建bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆