[英]How to provide single bean definition for all child class in spring configuration?
I am new to spring and exploring it, I want to my spring container to create all objects from a specific package. 我是Spring的新手,正在探索它,我想在Spring容器中从特定的包创建所有对象。
Circle Class: 圈子类别:
@Component
public class Circle extends AbstractShape {
@Override
public void draw() {
}
@Override
public int calculateArea(int x, int y) {
return (int) (3.14 * x * y);
}
} }
Square Class: 方类:
@Component
public class Square extends AbstractShape {
@Override
public void draw() {
}
@Override
public int calculateArea(int x, int y) {
return x * y;
}
}
My spring config class which basically create bean defination for me: 我的spring config类基本上为我创建了Bean defination:
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();
}
}
I want my bean definition to be created which extends class "AbstractShape", and want to avoid providing one by one bean definition in my config class. 我希望创建扩展类“ AbstractShape”的bean定义,并希望避免在config类中一一提供bean定义。 Please suggest possible ways to do so. 请提出可行的方法。
Thanks in Advance, 提前致谢,
Priyank Priyank
Annotating the class Circle
and Square
itself with @Component
is much easier for a task like this. 对于此类任务,使用@Component
注释类Circle
和Square
本身要容易得多。
This method is identical to declaring a method in a @Configuration
class, the way you are doing now. 此方法与在@Configuration
类中声明方法相同,即您现在的操作方式。
You can try annotating the AbstractShape
class, I don't know from the top of my head if it works 您可以尝试对AbstractShape
类进行注释,从我的头顶上不知道它是否有效
It got resolved by adding @ComponenetScan at configuration. 通过在配置中添加@ComponenetScan可以解决此问题。
Thanks for your answers. 感谢您的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.