admin管理员组

文章数量:1390391

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

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);
       }
   }
Share Improve this question asked Mar 14 at 8:38 BanupriyaBanupriya 1941 silver badge11 bronze badges 2
  • Hello banupriya , beyond the topic of your question, having a child class have an attribute with the same name as the parent class is a very, very bad idea. – Marce Puente Commented Mar 14 at 12:00
  • Got it thanks :) .. – Banupriya Commented Mar 17 at 8:43
Add a comment  | 

1 Answer 1

Reset to default 2

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

本文标签: javaConfiguration class extends Component class in springStack Overflow