最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Configuration class extends Component class in spring - Stack Overflow

programmeradmin4浏览0评论

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();
    }
}
发布评论

评论列表(0)

  1. 暂无评论