CAST Engineering Dashboard - Violations - False Violation - Avoid directly instantiating a Class used as a Spring bean
Description
When using explicit object constructors ((i.e. new
The goal of the quality rule “Avoid directly instantiating a Class used as a Spring bean” is to check for proper use of beans initialization and use.
The goal of beans in an application, is to provide a framework, to build objects and to set properties according to the configuration file.
Using an explicit object constructor violates this purpose, basically short-circuiting the bean framework that has been created. CAST in this case will flag this as a violation of this quality rule.
Observed in CAST Version
| Release | Yes/No |
|---|---|
| 8.3.x | ✅ |
Observed on RDBMS
| RDBMS | Yes/No |
|---|---|
| CSS | ✅ |
Step by Step Scenario
- Define at least one bean and associated framework in your code.
- Use new to instantiate a class
Action Plan
To resolve the violation, you should
Use either the spring bean factory to instantiate the object and set its properties according to spring configuration or call the spring application context getBean method .
You can see more on the getBean method here which may help clarify things
Your code could possibly look something like this:
public class MyBean implements MyBeanInterface { private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
public class AnotherClass { MyBeanInterface bean;
public MyBeanInterface getBean() {
return bean;
}
public void setBean(MyBeanInterface bean) {
this.bean = bean;
}
}
2. instead of doing:
new myBean();
**Impact on Analysis Results and Dashboard**
No impact - violations in this case are expected
**Notes/comments**
**Related Pages**
[CAST Engineering Dashboard - Violations - False violation or no violation](/export-v2/tg/technical-guides/technical-guides-by-cast-aip-component/cast-engineering-dashboard-component-ced/cast-engineering-dashboard-violations/cast-engineering-dashboard-violations-false-violation-or-no-violation/)