Spring踩坑:抽象类作为父类,使用子类@Autowired属性进行填充,属性值为null
    		       		warning:
    		            这篇文章距离上次修改已过421天,其中的内容可能已经有所变动。
    		        
        		                
                解释:
在Spring框架中,使用@Autowired注解自动填充属性时,如果属性是定义在抽象类中,并且该抽象类被具体子类继承,在尝试使用子类进行自动装配时可能会遇到问题,导致属性值为null。这通常是因为Spring容器在实例化子类时不会主动去查找并填充定义在父类抽象类中的@Autowired属性。
解决方法:
- 使用@Autowired注解的required属性设置为false,并提供一个默认的无参构造器。
- 使用@PostConstruct注解的方法来在属性填充之后进行初始化。
- 使用@Resource或@Inject注解来显式指定要装配的bean。
- 使用@Component注解标注抽象类,并确保子类也是一个标准的Spring组件(使用@Component、@Service、@Repository或@Controller注解)。
- 使用ApplicationContext手动获取需要的bean。
示例代码:
@Component
public class ConcreteClass extends AbstractClass {
    // 确保有默认的无参构造器
 
    @Autowired
    public void setDependency(Dependency dependency) {
        super.setDependency(dependency);
    }
 
    @PostConstruct
    public void init() {
        // 在这里可以确保依赖已经被注入
    }
}
 
public abstract class AbstractClass {
    private Dependency dependency;
 
    // 确保有默认的无参构造器
 
    // 设置依赖的方法,子类通过@Autowired调用此方法进行注入
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    }
 
    // 抽象类中可以有抽象方法,子类需要实现它们
}在这个例子中,子类通过@Autowired标注的方法来注入依赖,这样父类中的dependency属性就能够被正确地注入。
评论已关闭