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
- https://www.baeldung.com/spring-beancreationexception#2-javalanginstantiationexception
- https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s06.html#:~:text=The%20parent%20bean%20cannot%20get,parent%20definition%20for%20child%20definitions.
- https://www.baeldung.com/spring-bean-annotations
- https://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in#:~:text=Technically%2C%20there%20is%20no%20difference,and%20within%20the%20defined%20layer.
- https://stackoverflow.com/questions/31043865/java-lang-instantiationexception-with-abstract-class-using-conponent-scan