Description

 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.

Observed in CAST Version
Release
Yes/No
8.3.x(tick)
Observed on RDBMS
RDBMS
Yes/No
CSS(tick)
Step by Step Scenario
  1. Define at least one bean and associated framework in your code.
  2. Use new to instantiate a class
Action Plan

To resolve the violation, you should

  1. 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;
        }
    }
    
  2. instead of doing:

    new myBean();


Impact on Analysis Results and Dashboard

No impact - violations in this case are expected

Notes/comments