Java Spring、抽象类和注解
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2921899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring, abstract class and annotations
提问by onigunn
I've got a pretty simple abstract class
我有一个非常简单的抽象类
public abstract class AbstractServiceActions {
@Autowired
protected DatabaseModel dbModel;
protected User user;
protected boolean complete;
protected String serviceResult;
public AbstractServiceActions(User user) {
this.user = user;
this.serviceResult = "";
}
public abstract String doAction();
}
Now you can see, I'm trying to autowire the DatabaseModel. But in my extended class I only recieve null for the dbModel.
现在您可以看到,我正在尝试自动装配 DatabaseModel。但是在我的扩展类中,我只收到 dbModel 的 null。
@Component
public class CreateDatabaseAction extends AbstractServiceActions {
....
}
Question: Am I trying something impossible here?
问题:我在这里尝试了不可能的事情吗?
采纳答案by Bozho
Your setup seems fine. The reason perhaps lies elsewhere. Maybe you are instantiating the class with new CreateDatabaseAction(), rather than letting spring do this.
你的设置看起来不错。原因或许在别处。也许您正在使用 实例化类new CreateDatabaseAction(),而不是让 spring 这样做。
回答by Viswanath
Use @Autowiredand not @Injectfrom javax.inject.
使用@Autowired而不是@Inject来自javax.inject.
Dependency injection in abstract class only works for spring's @Autowired.
抽象类中的依赖注入仅适用于 spring 的@Autowired.
FYI, I'm using Spring 4.0; Java 6
仅供参考,我使用的是 Spring 4.0;爪哇 6

