I have a question. Why is this repository not null here.
@Component
public class InitialStartUp implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private DigitalsRepository digitalsRepository; // <--- NOT NULL
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
}
}
But here it will become null.
@Getter
public class DigitalsView extends HorizontalLayout{
/**
*
*/
private static final long serialVersionUID = 1L;
@Autowired
private DigitalsRepository digitalsRepository; // <-- This is null
public DigitalsView() {
}
}
I have created the repository here
@Repository
public interface DigitalsRepository extends JpaRepository<Digitals, Long> {
Digitals findByid(int i);
}
So why does this happen?
I can use digitalsRepository
at the class InitialStartUp
but not at the DigitalsView
class. Why?
Update:
Here is a real working example where @Autowired becomes null, and not null. It's the main view where it takes time for Spring to auto wire a field so it won't become null. From the beginning, it will become null. But if I use the listener below, it will show that it will be not null.
@Route("")
@Viewport("width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes, viewport-fit=cover")
@PWA(name = "My Application", shortName = "My App")
public class MainView extends AppLayout {
/**
*
*/
private static final long serialVersionUID = 1L;
private LineChart lineChart = new LineChart();
private DigitalOutputs digitalOutputs = new DigitalOutputs();
private ControlPanel controlPanel = new ControlPanel(lineChart);
private Image pinMap;
@Autowired
private DigitalsRepository digitalsRepository;
public MainView() {
System.out.println(null == digitalsRepository); // THIS IS NULL
// Bar
Image img = new Image("img/JLogger.png", "JLogger Logo");
img.setHeight("100px");
addToNavbar(img);
// Pin map
pinMap = new Image("img/Pinmap.png", "Pinmap");
// Tabs
Tabs tabs = new Tabs(new Tab("Plot"), new Tab("Digitals"), new Tab("Pin map"), new Tab("Logout"));
tabs.setOrientation(Tabs.Orientation.VERTICAL);
HorizontalLayout contents = new HorizontalLayout();
contents.add(lineChart, digitalOutputs.getGrid(), controlPanel.getLayout(), pinMap);
// Include
addToDrawer(tabs);
setContent(contents);
// Listener for the tabs
tabs.addSelectedChangeListener(click -> {
// Show a selection
int selectedIndex = tabs.getSelectedIndex();
switch(selectedIndex) {
case 0: // Plot
hideAll();
lineChart.getChart().setVisible(true);
controlPanel.getLayout().setVisible(true);
System.out.println(null == digitalsRepository); // NOT NULL
break;
case 1: // Digitals
hideAll();
digitalOutputs.getGrid().setVisible(true);
break;
case 2: // Pin map
hideAll();
pinMap.setVisible(true);
break;
case 3: // Logout
UI.getCurrent().navigate(SecurityConfiguration.LOGOUT_URL.replace("/", ""));
break;
}
});
}