javaspringspring-boot

Configuration class extends Component class in spring


I understand that it is not a good practice for a configuration class to extend component class. As i am not creating any beans in configuration class, will there be any issues with proxies?

    @Component
    public class BaseComponent {  
      Objectmapper ob; 
      
       @Autowired
       public  BaseComponent(Objectmapper ob) { 
         this.ob=ob;
        }
    }
    
    @Configuration
    public class ConfigClass extends BaseComponent 
    {       
      Objectmapper ob; 
       @Autowired 
        public  ConfigClass(Objectmapper ob) 
       {   
        super(ob);
       }
   }

Solution

  • The BaseComponent class, being a Component, is also a Spring Bean with potential separate lifecycle and injection by Spring. This could lead to proxy conflicts or unexpected bean resolution. Configuration classes are managed as CGLIB proxies to ensure singleton beans. Extending from a Component can interfere with this proxying, causing unexpected behavior if the parent class's logic is involved.

    Instead of having the ConfigClass extend BaseComponent, inject the BaseComponent into the ConfigClass:

    @Component
    public class BaseComponent {
        private final ObjectMapper objectMapper;
    
        @Autowired
        public BaseComponent(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
        }
    
        public ObjectMapper getObjectMapper() {
            return objectMapper;
        }
    }
    
    @Configuration
    public class ConfigClass {
        private final BaseComponent baseComponent;
    
        @Autowired
        public ConfigClass(BaseComponent baseComponent) {
            this.baseComponent = baseComponent;
        }
    
        public ObjectMapper getObjectMapper() {
            return baseComponent.getObjectMapper();
        }
    }