我在显示数据库中的值时遇到问题。
我有:
@SpringUI(path="order")
public class OrderGUI extends UI
与构造函数:
public OrderGUI()
{
navigator = new Navigator(this, this);
navigator.addView("GetOrderNumber", GetOrderNumber.class);
navigator.addView("allpurchasers", AllPurchasersGUI.class);
}
在@SpringView的GetOrderNumber类中,我尝试在单击Button后导航到AllPurchasersGUI:
allPurchasers = new Button("See all purchasers");
allPurchasers.addClickListener(e -> //getUI().getPage().setLocation("allpurchasers")
getUI().getNavigator().navigateTo("allpurchasers")
);
这是个大问题,因为在AllPurchasersGUI中:
@Autowired
private final OrderRepository orderRepository;
当我有构造函数的参数时:
public AllPurchasersGUI(OrderRepository or) {
System.out.println("allpurchasers");
this.orderRepository = or;
this.grid = new Grid<>(Order.class);
grid.setSizeFull();
}
没关系,但是Vaadin强迫我添加不带参数的构造函数,但是随后我需要初始化orderRepository,这样我会得到一个错误:
Error:(26, 5) java: variable orderRepository might not have been initialized
有什么选择可以避免默认构造函数?还是有其他解决方案?
@编辑
AllPurchasersGUI类:
package purchasers;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.*;
import order.Order;
import order.OrderRepository;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@SpringView(name="allpurchasers")
public class AllPurchasersGUI extends VerticalLayout implements View {
/*@Autowired
private final OrderRepository orderRepository;*/
final Grid<Order> grid;
public AllPurchasersGUI()
{
System.out.println("allpurchasers");
this.grid = new Grid<>(Order.class);
grid.setSizeFull();
}
public AllPurchasersGUI(OrderRepository or) {
System.out.println("allpurchasers");
//this.orderRepository = or;
this.grid = new Grid<>(Order.class);
grid.setSizeFull();
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent event)
{
Notification.show("Im in all purchasers");
listPurchasers();
}
/**
* method to display orders in grid
*/
private void listPurchasers()
{
//List<Order> allOrders = (List<Order>) orderRepository.findAll();
Order order = new Order("mwalko", 123L, "klapa", LocalDate.now());
List<Order> allOrders = new ArrayList<Order>();
allOrders.add(order);
grid.setItems(allOrders);
grid.setColumns("id", "login", "dateOfOrder");
addComponent(grid);
}
}
和删除无参数的构造函数时的错误:
java.lang.IllegalArgumentException: Unable to create an instance of {0}. Make sure the class has a public no-arg constructor.
最佳答案
如果您被迫使用no-arg构造函数,则可以使用它并使用@Autowired注释按字段注入OrderRepository。
但是,直到您的字段被声明为最终字段,您才能执行此操作。
我希望按构造函数注入依赖关系,但在这种情况下,您可以使用字段注入。