问题描述
好的,所以标题可能不是最好的,但我在这里露面了。所以我的Vaadin应用程序是一页,没有其他路由。尽管Web应用程序是一页,但我还是选择了根据布局将页面分为不同的类,等等。有一个名为MainLayout.class的主类,它具有@Route(“”)。
这里是网站的概述,每个概述都代表一个新类,该类会延长组件的使用时间。 (缺少下半部分以保持简单性。)
现在的问题是,红色和蓝色组件都使用依赖注入来注入所需的服务。一切都很好,但是当 purple 布局想要保留Red和Blue类的实例,以便可以向其自身添加组件时,就会出现问题。
我当前的方法: 我当前的方法非常hacky和错误,只是通过将蓝色和红色组件类注入到紫色类的构造函数中来再次使用依赖项注入。这个过程一直持续到到达MainLayout类为止。
我的问题: 还有其他解决方案,如果可以,我应该如何或在何处解决该问题?
主布局类:(它使用依赖项注入来获取所有其他还包含子组件等的子布局)
@Route("")
@PageTitle("Ur Weather App")
@CssImport("./styles/shared-styles.css")
@PreserveOnRefresh
public class MainLayout extends VerticalLayout {
private static final long serialVersionUID = 1L;
private final NavigationView searchBar;
private final CurrentInfoLayout currentInfoLayout;
private final MoreDetailInfoLayout moreDetailInfoLayout;
@Autowired
public MainLayout(NavigationView searchBar,CurrentInfoLayout currentInfoLayout,MoreDetailInfoLayout moreDetailInfoLayout) {
this.searchBar = searchBar;
this.currentInfoLayout = currentInfoLayout;
this.moreDetailInfoLayout = moreDetailInfoLayout;
addClassName("main-layout");
add(this.searchBar,this.currentInfoLayout,this.moreDetailInfoLayout);
}
}
红色组件:(蓝色组件在某种程度上相似)
@Component
@UIScope
@CssImport("./styles/current-info-styles.css")
public class CurrentDayView extends VerticalLayout {
private static final long serialVersionUID = 1L;
private NowcastWeatherService NowcastWeatherService;
private GeoLocationService geoLocationService;
//Some other code here
@Autowired
public CurrentDayView(NowcastWeatherService NowcastWeatherService,GeoLocationService geoLocationService) {
this.NowcastWeatherService = NowcastWeatherService;
this.geoLocationService = geoLocationService;
//Other functionality here
}
//Other code here
}
紫色组件:(这是使用依赖项注入来获取其他组件。)
@Component
@UIScope
@CssImport("./styles/current-info-styles.css")
public class CurrentInfoLayout extends HorizontalLayout {
private CurrentDayView currentDayView;
private CurrentTemperatureView currentTemperatureView;
@Autowired
public CurrentInfoLayout(CurrentDayView currentDayView,CurrentTemperatureView currentTemperatureView) {
this.currentDayView = currentDayView;
this.currentTemperatureView = currentTemperatureView;
this.searchBar = searchBar;
//Other functionality here
}
//Other code here
}
您可能会说,我对其中的大多数内容相当了解,因此我可能不知道依赖项注入的最佳策略,等等。 谢谢您的时间!
解决方法
从spring和依赖注入的角度来看(我没有与Vaadin合作),您做对了。您正在通过构造函数进行注入,这是推荐的方法。您可以做的更多事情是像在final
中一样,将MainLayout
关键字添加到注入的属性中。
如果要避免使用依赖项注入,可以在实例化父组件时使用Singleton
模式来检索所需组件的实例。