CRITICAL
Rule Definition
When a class is used to instantiate a Spring bean, this bean benefits from different Spring key features:
* Each bean is a Spring component and can take advantage of all Spring services, such as declarative transaction management
* Each public bean's method is added to the Spring container, so it's eligible for injection into other objects, JMX export and other benefits.
So, if a class is instantiated as a Spring bean and as a direct Java instance at the same time, for these two instances, you may see different and unpredictable behavior.
Remediation
Use only Spring beans and when you need different instances of the same class, use the prototype mode attribute.
Violation Code Sample
<bean id="myBean" class="sample.MyBean">
<property name="url">
<value>http://localhost/myBeanService</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 {
MyBean bean;
AnotherClass() {
bean = new MyBean(); // VIOLATION
}
}
Fixed Code Sample
<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;
}
}
Related Technologies
JEE
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.