How to create bean using @Bean in spring boot for abstract class

前端 未结 3 559
旧巷少年郎
旧巷少年郎 2021-01-11 09:02

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

Here my ask , how to conver

3条回答
  •  广开言路
    2021-01-11 09:59

    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.

    Then you have two ways :

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

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

    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.

提交回复
热议问题