Spring 可以在抽象类中自动装配吗? [英] Spring can you autowire inside an abstract class?
问题描述
Spring 无法自动装配我的对象?是否可以在抽象类中自动装配对象.假设所有模式都在 application-context.xml
Spring is failing to autowire my object? Is it possible to autowire an object within an abstract class. Assume all schemas are supplied in application-context.xml
问题:在基类和扩展类(如果有)@Service @Component 上应该使用什么注解?
Question: What annotation should be on the base and extending classes (if any) @Service @Component?
示例
abstract class SuperMan {
@Autowire
private DatabaseService databaseService;
abstract void Fly();
protected void doSuperPowerAction(Thing thing) {
//busy code
databaseService.save(thing);
}
}
拓展课程
public class SuperGirl extends SuperMan {
@Override
public void Fly() {
//busy code
}
public doSomethingSuperGirlDoes() {
//busy code
doSuperPowerAction(thing)
}
application-context.xml
<context:component-scan base-package="com.baseLocation" />
<context:annotation-config/>
推荐答案
通常情况下,Spring 应该进行自动装配,只要您的抽象类在为组件扫描提供的基础包中即可.
Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.
See this and this for further reference.
@Service
和 @Component
都是在 Spring 容器内创建注释类型 bean 的构造型.正如 Spring Docs 所述,
@Service
and @Component
are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,
这个注解作为@Component的特化,允许通过类路径扫描自动检测实现类.
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
这篇关于Spring 可以在抽象类中自动装配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!