Correctness8 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki

Bug pattern name: ABSTRACT_CLASS_BEAN Short Description: Bean should not be an abstract class.

Description

"an abstract class isn't component-scanned since it can't be instantiated without a concrete subclass."

@Component
public abstract class BeanA implements IBeanA { ... }
================================================================
<bean id="beanA" class="com.baeldung.web.BeanA" />
================================================================
@Configuration
public class Config {
    @Autowired
    BeanFactory beanFactory;

    @Bean
    public BeanB beanB() {
        beanFactory.getBean("beanA"); // error occurs
        return new BeanB();
    }
}
// Test code

//Sample Code To Test 
public class ConstructorMain {
    public static void main(String[] args) throws ClassNotFoundException {
        GenericApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        BeanA bean = (BeanA) ctx.getBean("beanA");
    }
}
//--------------------------------------------
@Configuration
@ComponentScan(basePackages = "com.example.myspringdemo1.constructor")
class AppConfig {}
@Component
public class BeanB {} // no error occurred
//--------------------------------------------
@Component
public class BeanA {
    BeanB beanB;

    @Autowired
    public BeanA(BeanB beanB) { 
        this.beanB = beanB;
    }
}
//--------------------------------------------
@Component
public abstract class BeanB {} // error occurred

Implement Strategy

  • Find classes annotated with @Component, @Service, @Repository and @Controller. Or @Bean (in @Cofiguration class).
  • Check if any of them is an abstract class

Reference List