简体   繁体   English

在抽象类中自动装配 null

[英]autowire null in the abstract class

I had an issue to autowire an object in my abstract base class.我在抽象基类中自动装配对象时遇到问题。 It always give me null instead of an instance.它总是给我 null 而不是一个实例。 Please help.请帮忙。

Base class:基类:

public abstract class BaseClass implements IReq<Req> {

    @Autowired
    protected ReqDao dao;

    protected void updateReq() {
         dao.update();
    } 
}

Child class:儿童班:

@Component
public class ChildClass extends BaseClass {
    ...
}

ReqDao class: ReqDao 类:

@Component
public class RptRequestDao {
     public void update(){
          ...
     }
}

I am thinking of simply use the update() function in Base class, which means in my ChildClass, I don't override that one.我想在 Base 类中简单地使用 update() 函数,这意味着在我的 ChildClass 中,我不会覆盖那个。 Is this the problem?这是问题吗? If it is, what's the normal way to do it?如果是,通常的做法是什么? Thanks in advance.提前致谢。

A bean is created on demand, in your case when you initialize your object, RepoDao is private so it wont be inhereted to the class which will be intialized, you either need to put一个 bean 是按需创建的,在你初始化对象的情况下,RepoDao 是私有的,所以它不会被继承到将被初始化的类,你要么需要把

@Component
public class ChildClass extends BaseClass {
    @Autowired
    private ReqDao dao;

or make it protected/public in BaseClass, sure public will make it accessible to other classes which violates the encapsulation或在 BaseClass 中将其设置为 protected/public,确保 public 将使其他违反封装的类可以访问它

Instantiate your child class using @Autowired like this像这样使用@Autowired 实例化您的子类

public class SomeClass{

@Autowired
ChildClass childClass; //IMPORTANT

}

The error occurs when you try to instantiate the childClass like this:当您尝试像这样实例化 childClass 时会发生错误:

public class SomeClass{

ChildClass childClass = new ChildClass();

}

BaseClass 是抽象的,你不能实例化它。你需要在 ChildClass 中让你的 ReqDao 被自动装配。Spring 只会在它创建该类的实例时自动装配。希望有帮助

Check how you are instantiating the child class.检查您如何实例化子类。 Make sure you are NOT using "new" keyword to instantiate child class.确保您没有使用“new”关键字来实例化子类。

ChildClass cc = new ChildClass() // **Not recommended**

You must autowire the childclass and let spring take care of bean creation.您必须自动装配子类并让 spring 负责创建 bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM