When using explicit object constructors ((i.e. new <object>), you get violations for the quality rule "Avoid directly instantiating a Class used as a Spring bean".
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.
Release | Yes/No |
---|---|
8.3.x |
RDBMS | Yes/No |
---|---|
CSS |
- Define at least one bean and associated framework in your code.
- Use new to instantiate a class
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:<bean id="myBean" class="sample.MyBean"> <property name="url"> <value>http://localhost/myBeanService</value> </property> </bean> <bean id="anotherClass" class="sample.AnotherClass"> // FIXED <property name="bean"> <value>myBean</value> </property> </bean> 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; } }
instead of doing:
new myBean();
No impact - violations in this case are expected