问题描述
我需要在启动时使用带有构造函数参数的Spring Boot初始化以下 PointQuadTree
类,并使该对象在整个应用程序中可用。构造函数参数'minX,maxX,...'需要来自application.properties文件。
I need to initialize the following PointQuadTree
class on startup using Spring Boot with constructor parameters, and make the object available throughout the application. The constructor parameters 'minX, maxX, ...' need to come from the application.properties file.
PointQuadTree
public class PointQuadTree<T extends PointQuadTree.Item> {
private final Bounds mBounds;
public PointQuadTree(double minX, double maxX, double minY, double maxY) {
this(new Bounds(minX, maxX, minY, maxY));
}
...
}
Bounds
public class Bounds {
public final double minX;
public final double minY;
public final double maxX;
public final double maxY;
public final double midX;
public final double midY;
public Bounds(double minX, double maxX, double minY, double maxY) {
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
midX = (minX + maxX) / 2;
midY = (minY + maxY) / 2;
}
...
}
我尝试用 @Component
注释 PointQuadTree
,但是没有没有参数的构造函数。即使我添加没有参数的构造函数 Bounds
是 final
,所以在之后无法设置它PointQuadTree
已初始化。另外 Bounds
有一个只带参数的构造函数。
I've tried annotating PointQuadTree
with @Component
, but there is not constructor without parameters. Even if I add a constructor without parameters Bounds
is final
, so it cannot be set after PointQuadTree
is initialized. Also Bounds
has a constructor with parameters only.
之后> PointQuadTree
被初始化,我需要它坐在内存中,需要能够在其他组件中自动装配它来读取/删除/添加项目。我不知道如何使用Spring Boot执行此操作。任何帮助都非常感激。
After PointQuadTree
is initialized, I need it to sit in memory and need to be able to autowire it in other components to read/remove/add items. I have no idea how to do this with Spring Boot. Any help greatly appreciated.
推荐答案
这就像在Spring中创建bean一样简单......
This is as simple as creating beans in Spring way...
@Configuration
public class AppBeans{
@Value("${minx:100}")
private double minX;
...so on ..
@Bean
public PointQuadTree pointQuadTree()
{
return new PointQuadTree(minX...so on);
}
}
并将此bean注入您想要的位置使用 @Autowired
and inject this bean where you want using @Autowired
此处 $ {minx:100}
,尝试从属性文件中读取,如果未指定,则默认为 100
Here ${minx:100}
, tries to read from properties file, if not specified takes the default as 100
这篇关于Spring启动时使用构造函数参数初始化bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!