Java 如何在spring配置中为所有子类提供单个bean定义?
我是spring新手,正在探索它,我希望使用spring容器从特定的包中创建所有对象 圆圈类:Java 如何在spring配置中为所有子类提供单个bean定义?,java,spring,spring-boot,dependency-injection,inversion-of-control,Java,Spring,Spring Boot,Dependency Injection,Inversion Of Control,我是spring新手,正在探索它,我希望使用spring容器从特定的包中创建所有对象 圆圈类: @Component public class Circle extends AbstractShape { @Override public void draw() { } @Override public int calculateArea(int x, int y) { return (int) (3.14 * x * y); } } 方形类: @Component publi
@Component
public class Circle extends AbstractShape {
@Override
public void draw() {
}
@Override
public int calculateArea(int x, int y) {
return (int) (3.14 * x * y);
}
}
方形类:
@Component
public class Square extends AbstractShape {
@Override
public void draw() {
}
@Override
public int calculateArea(int x, int y) {
return x * y;
}
}
基本上为我创建bean定义的spring配置类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShapeConfig {
@Bean
public Circle getCircle() {
return new Circle();
}
@Bean
public Square getSquare() {
return new Square();
}
}
我希望创建扩展类“AbstractShape”的bean定义,并希望避免在配置类中逐个提供bean定义。请提出可能的方法
提前感谢,
Priyank用
@组件
注释类圆
和方
本身对于这样的任务来说要容易得多
此方法与在@Configuration
类中声明方法相同,就像您现在所做的那样
您可以尝试注释
抽象形状
类,我不知道它是否有效用@组件
注释类圆形
和方形
本身对于这样的任务来说要容易得多
此方法与在@Configuration
类中声明方法相同,就像您现在所做的那样
您可以尝试注释
AbstractShape
类,我不知道它是否有效通过在配置中添加@ComponenetScan解决了这个问题
感谢您的回答。通过在配置中添加@ComponenetScan解决了这个问题
谢谢您的回答。我不确定您是否正确-但为什么您不能将圆形和方形注释为@Component?很抱歉,我错过了这一部分。我已经注释为@Component。我不确定我是否理解正确-但为什么不能将圆形和方形注释为@Component?很抱歉,我错过了这一部分。我已经注释为@Component。我已经将“圆”和“方”标记为@Component。注释抽象类不是一个好主意。因为你不能实例化一个抽象类。我已经把“圆”和“方”标记为@Component。注释抽象类不是一个好主意。因为您不能实例化抽象类。