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
1 Answer
Reset to default 2The 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
版权声明:本文标题:java - Configuration class extends Component class in spring - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744667220a2618605.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论