【问题标题】:Spring MVC: Dijkstra's algorithm how to create a bean for graph on startupSpring MVC:Dijkstra 的算法如何在启动时为图形创建 bean
【发布时间】:2016-02-16 00:50:26
【问题描述】:

当我在两点之间求解 Dijkstra 算法时,我必须在运行它时再次创建图形对象。我想创建一个 spring MVC 应用程序,该图在启动时作为 bean 加载一次。

目前这些是我的课程的样子:

public class Graph {
private final List<Vertex> vertexes;

public Graph(List<Vertex> vertexes) {
                this.vertexes = vertexes;


public List<Vertex> getVertexes() {
                return vertexes;
}    
}

顶点类:

public class Vertex implements Comparable<Vertex> {

final private Integer id;
final private String name;
public List<Edge> adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;

public Vertex(Integer id, String name) {
           this.id = id;
           this.name = name;
           adjacencies = new LinkedList<Edge>();
         }

public Integer getId() {
       return id;
}

public String getName() {
       return name;
}

@Override
public String toString() {
   return id+name;
}

public int compareTo(Vertex other) {
    return Double.compare(minDistance, other.minDistance);
}

}

边缘类:

public class Edge {
private final String id;
private final Vertex destination;
private final double weight;

public Edge(String id, Vertex destination, double weight) {
       this.id = id;
       this.destination = destination;
       this.weight = weight;
}

public String getId() {
       return id;
}


public Vertex getDestination() {
       return destination;
}

public double getWeight() {
       return weight;
}

}

在我的主要方法中,我用 274 个顶点元素填充顶点列表。然后 Graph 类在其构造函数中获取此列表。如何将这个单个图形对象创建为 bean?这是我所知道的。

<bean id="graph" class="com.fdm.model.Graph" >
<constructor-arg ref="list"/>
</bean>

<util:list id="list" list-class="java.util.ArrayList" />

但我不确定如何进一步进行。上面的列表不是vertex类型的吗?

【问题讨论】:

  • 将Graph 定义为静态?

标签: java spring algorithm spring-mvc graph


【解决方案1】:

在这里,您在应用程序上下文中创建了一个具有单例范围的 bean。 此外,您还连接了一个引用 Vertexes bean 列表的构造函数参数。

<bean id="graph" class="com.fdm.model.Graph" > 
 <constructor-arg ref="list"/> 
</bean>

spring 中的 bean 默认是单例的。

在这里,您创建了一个 id 为 list 的列表 bean,在这里您可以定义顶点的值类型。同样在这种情况下,此列表的范围是单例 如果要定义类型

<util:list id="list" value-type="com.springapp.mvc.Vertex" list-class="java.util.ArrayList" />

您还可以查看以下示例 How to define a List bean in Spring?

【讨论】:

    猜你喜欢
    • 2017-01-08
    • 1970-01-01
    • 2021-03-18
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多