Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot initializing bean at startup with constructor parameters

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;
   }

   ...
}

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.

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.

like image 214
Jerry Avatar asked Jan 21 '15 06:01

Jerry


2 Answers

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);
   }

}

and inject this bean where you want using @Autowired

Here ${minx:100}, tries to read from properties file, if not specified takes the default as 100

like image 183
Jayaram Avatar answered Oct 17 '22 00:10

Jayaram


in some configuration file create a spring bean of tree, something like this:

@Configuration
public class PointQuadTreeBeans
{

   @Bean(name="theSameTree")
   public PointQuadTree getPointQuadTree(Environment env)
   {
      double minX = env.getProperty("minX");
      double maxX = env.getProperty("maxX");
      double minY = env.getProperty("minY");
      double maxY = env.getProperty("maxY");
      PointQuadTree tree = new PointQuadTree(minX, maxX, minY, maxY);
   }


}

and add this class to spring componentScan

UPD

another way:

instead of double minX = env.getProperty("minX"); you can create fields with @Value, like @chrylis said in comment:

@Value("${minX}")
private double minX;

then use it field to create bean.

like image 32
Cuzz Avatar answered Oct 16 '22 22:10

Cuzz