Services Bean can not autowired in some classes

Hi, I can do autowired services beans in my ApplicationUI (here works fine and I can load data from database) but I can not do it in my others classes and always the service bean is null. I attached files and below is the app structure.

I will appreciate any help to check what I missing or doing wrong…

sicovi
.com
  .syshace
    .sicovi
      Application.java 
      ApplicationUI.java <- here works fine 
      .backend 
        .entity 
          Resident.java 
        .repository 
          ResidentRepository.java 
        .service 
          ResidentService.java 
          ResidentServiceImpl.java 
      .webui 
        .view 
          ResidentView.java <- doesn't do autowired from here
2018-08-06 17:26:43.785 ERROR 19840 --- [nio-8080-exec-7]
 com.vaadin.server.DefaultErrorHandler    : 

java.lang.IllegalArgumentException: Unable to create an instance of {0}. The constructor threw an exception.
	at com.vaadin.util.ReflectTools.createInstance(ReflectTools.java:298) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.navigator.Navigator$ClassBasedViewProvider.getView(Navigator.java:412) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.syshace.sicovi.webui.navigator.ApplicationNavigator$2.getView(ApplicationNavigator.java:99) ~[classes/:na]

	at com.vaadin.navigator.Navigator.navigateTo(Navigator.java:652) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.syshace.sicovi.webui.view.MainView$MainMenu$ValoMenuItemButton$1.buttonClick(MainView.java:242) ~[classes/:na]

	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]

	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]

	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]

	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]

	at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:499) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:273) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:237) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1014) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.ui.Button.fireClick(Button.java:384) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.ui.Button$1.click(Button.java:57) ~[vaadin-server-8.5.1.jar:8.5.1]

	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]

	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]

	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]

	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]

	at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:155) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:116) ~[vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:445) [vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:410) [vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:274) [vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90) [vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40) [vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1601) [vaadin-server-8.5.1.jar:8.5.1]

	at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:445) [vaadin-server-8.5.1.jar:8.5.1]

	at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]

	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]

	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]

	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]

	at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

Caused by: java.lang.reflect.InvocationTargetException: null
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_121]

	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_121]

	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_121]

	at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_121]

	at com.vaadin.util.ReflectTools.createInstance(ReflectTools.java:276) ~[vaadin-server-8.5.1.jar:8.5.1]

	... 65 common frames omitted
Caused by: java.lang.NullPointerException: null
	at com.syshace.sicovi.webui.view.ResidentView.refreshData(ResidentView.java:69) ~[classes/:na]

	at com.syshace.sicovi.webui.view.ResidentView.buildGrid(ResidentView.java:161) ~[classes/:na]

	at com.syshace.sicovi.webui.view.ResidentView.<init>(ResidentView.java:63) ~[classes/:na]

	... 70 common frames omitted

17202004.xml (3.79 KB)
17202007.java (316 Bytes)
17202010.java (5.39 KB)
17202013.java (4.14 KB)
17202016.java (318 Bytes)
17202019.java (345 Bytes)
17202022.java (976 Bytes)
17202025.java (10.2 KB)

Hi,

I don’t know how you call ResidentView (not in your ApplicationUI) but you should inject our view (not create your view with new ResidentView).

You have a documentation here https://vaadin.github.io/spring-tutorial/

Hi Gueriaud, I took the [dashboard]
(https://demo.vaadin.com/dashboard/) demo ([code]
(https://github.com/vaadin/dashboard-demo)) to construct my project and the ResidentView is called as TransactionView is in the dashboard. The ResidentView is called through a MenuItem from MainView.

Either in my MainView or ResidentView doesn’r works the autowired, but in ApplicationUI works fine:

Here is my MainView class:

package com.syshace.sicovi.webui.view;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.eventbus.Subscribe;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.spring.annotation.UIScope;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
import com.syshace.sicovi.backend.entity.AuthenticationUser;
import com.syshace.sicovi.backend.entity.Residential;
import com.syshace.sicovi.backend.service.ResidentialService;
import com.syshace.sicovi.util.I18Labels;
import com.syshace.sicovi.webui.event.ApplicationEvent.NotificationsCountUpdatedEvent;
import com.syshace.sicovi.webui.event.ApplicationEvent.PostViewChangeEvent;
import com.syshace.sicovi.webui.event.ApplicationEvent.ProfileUpdatedEvent;
import com.syshace.sicovi.webui.event.ApplicationEvent.ReportsCountUpdatedEvent;
import com.syshace.sicovi.webui.event.ApplicationEvent.UserLoggedOutEvent;
import com.syshace.sicovi.webui.event.ApplicationEventBus;
import com.syshace.sicovi.webui.navigator.ApplicationNavigator;
import com.syshace.sicovi.webui.window.ProfilePreferencesWindow;

@UIScope  // ******** I TRIED TO USES THIS BUT SAME ERROR
public class MainView extends HorizontalLayout {

  private static final long serialVersionUID = -6563708086408200079L;
  private final I18Labels Labels = (I18Labels) VaadinSession.getCurrent().getAttribute("I18Labels");

  @Autowired
  private ResidentialService residentialService;  // ******** HERE IS MY AUTOWIRED SERVICE DECLARATION BUT DOESN'T WORKS 

  public MainView() {
    setSizeFull();
    addStyleName("mainview");
    setSpacing(false);

    Residential r = residentialService.get(1); // ******* HERE IS SEND ME A NULL POINTER ERRO 
    System.out.println(r);
    
    addComponent(new MainMenu());

    ComponentContainer content = new CssLayout();
    content.addStyleName("view-content");
    content.setSizeFull();
    addComponent(content);
    setExpandRatio(content, 1.0f);

    new ApplicationNavigator(content);
  }

  public final class MainMenu extends CustomComponent {
    private static final long serialVersionUID = -8903304297900219229L;

    public static final String ID = "application-menu";
    public static final String REPORTS_BADGE_ID = "application-menu-reports-badge";
    public static final String NOTIFICATIONS_BADGE_ID = "application-menu-notifications-badge";

    private static final String STYLE_VISIBLE = "valo-menu-visible";
    
    private Label notificationsBadge;
    private Label reportsBadge;
    private MenuItem settingsItem;
    
    public MainMenu() {
      setPrimaryStyleName("valo-menu");
      setId(ID);
      setSizeUndefined();

      // There's only one DashboardMenu per UI so this doesn't need to be
      // unregistered from the UI-scoped DashboardEventBus.
      ApplicationEventBus.register(this);
      setCompositionRoot(buildContent());
    }

    private Component buildContent() {
      final CssLayout menuContent = new CssLayout();
      menuContent.addStyleName("sidebar");
      menuContent.addStyleName(ValoTheme.MENU_PART);
      menuContent.addStyleName("no-vertical-drag-hints");
      menuContent.addStyleName("no-horizontal-drag-hints");
      menuContent.setWidth(null);
      menuContent.setHeight("100%");

      menuContent.addComponent(buildTitle());
      menuContent.addComponent(buildUserMenu());
      menuContent.addComponent(buildToggleButton());
      menuContent.addComponent(buildMenuItems());

      return menuContent;
    }

    private Component buildTitle() {
      Label logo = new Label("<strong>Control</strong> de Visitas", ContentMode.HTML);
      logo.setSizeUndefined();
      HorizontalLayout logoWrapper = new HorizontalLayout(logo);
      logoWrapper.setComponentAlignment(logo, Alignment.MIDDLE_CENTER);
      logoWrapper.addStyleName("valo-menu-title");
      logoWrapper.setSpacing(false);
      return logoWrapper;
    }

    private AuthenticationUser getCurrentUser() {
      return (AuthenticationUser) VaadinSession.getCurrent().getAttribute(AuthenticationUser.class.getName());
    }

    private Component buildUserMenu() {
      final MenuBar settings = new MenuBar();
      settings.addStyleName("user-menu");
      final AuthenticationUser user = getCurrentUser();
      settingsItem = settings.addItem("", new ThemeResource("images/profile-pic-300px.jpg"), null);
      updateUserName(null);
      settingsItem.addItem("Edit Profile", new Command() {
        private static final long serialVersionUID = 3923956725337580688L;

        @Override
        public void menuSelected(final MenuItem selectedItem) {
          ProfilePreferencesWindow.open(user, false);
        }
      });
      settingsItem.addItem("Preferences", new Command() {
        private static final long serialVersionUID = -1460709183140336227L;

        @Override
        public void menuSelected(final MenuItem selectedItem) {
          ProfilePreferencesWindow.open(user, true);
        }
      });
      settingsItem.addSeparator();
      settingsItem.addItem("Sign Out", new Command() {
        private static final long serialVersionUID = -8635177752954692536L;

        @Override
        public void menuSelected(final MenuItem selectedItem) {
          ApplicationEventBus.post(new UserLoggedOutEvent());
        }
      });
      return settings;
    }

    private Component buildToggleButton() {
      Button valoMenuToggleButton = new Button("Menu");
      valoMenuToggleButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = -331462190058291156L;

        @Override
        public void buttonClick(final ClickEvent event) {
          if (getCompositionRoot().getStyleName().contains(STYLE_VISIBLE)) {
            getCompositionRoot().removeStyleName(STYLE_VISIBLE);
          } else {
            getCompositionRoot().addStyleName(STYLE_VISIBLE);
          }
        }
      });
      valoMenuToggleButton.setIcon(VaadinIcons.LIST);
      valoMenuToggleButton.addStyleName("valo-menu-toggle");
      valoMenuToggleButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);
      valoMenuToggleButton.addStyleName(ValoTheme.BUTTON_SMALL);
      return valoMenuToggleButton;
    }

    private Component buildBadgeWrapper(final Component menuItemButton, final Component badgeLabel) {
      CssLayout badgeWrapper = new CssLayout(menuItemButton);
      badgeWrapper.addStyleName("badgewrapper");
      badgeWrapper.addStyleName(ValoTheme.MENU_ITEM);
      badgeLabel.addStyleName(ValoTheme.MENU_BADGE);
      badgeLabel.setWidthUndefined();
      badgeLabel.setVisible(false);
      badgeWrapper.addComponent(badgeLabel);
      return badgeWrapper;
    }

    private Component buildMenuItems() {
      CssLayout menuItemsLayout = new CssLayout();
      menuItemsLayout.addStyleName("valo-menuitems");

      for (final MainViewType view : MainViewType.values()) {
        Component menuItemComponent = new ValoMenuItemButton(view);

        if (view == MainViewType.BLACKLIST) {
          notificationsBadge = new Label();
          notificationsBadge.setId(NOTIFICATIONS_BADGE_ID);
          menuItemComponent = buildBadgeWrapper(menuItemComponent, notificationsBadge);
        }
        menuItemsLayout.addComponent(menuItemComponent);
      }
      return menuItemsLayout;
    }

    @Override
    public void attach() {
      super.attach();
      updateNotificationsCount(null);
    }

    @Subscribe
    public void postViewChange(final PostViewChangeEvent event) {
      // After a successful view change the menu can be hidden in mobile view.
      getCompositionRoot().removeStyleName(STYLE_VISIBLE);
    }

    @Subscribe
    public void updateNotificationsCount(final NotificationsCountUpdatedEvent event) {
      int unreadNotificationsCount = 2; // MainUI.getDataProvider().getUnreadNotificationsCount();
      notificationsBadge.setValue(String.valueOf(unreadNotificationsCount));
      notificationsBadge.setVisible(unreadNotificationsCount > 0);
    }

    @Subscribe
    public void updateReportsCount(final ReportsCountUpdatedEvent event) {
      reportsBadge.setValue(String.valueOf(event.getCount()));
      reportsBadge.setVisible(event.getCount() > 0);
    }

    @Subscribe
    public void updateUserName(final ProfileUpdatedEvent event) {
      AuthenticationUser user = getCurrentUser();
      settingsItem.setText(user.getFullname());
      settingsItem.setDescription(user.getRole().getName());
    }

    public final class ValoMenuItemButton extends Button {
      private static final long serialVersionUID = 5944927672148534319L;

      private static final String STYLE_SELECTED = "selected";
      private final MainViewType view;

      public ValoMenuItemButton(final MainViewType view) {
        this.view = view;
        setPrimaryStyleName("valo-menu-item");
        setIcon(view.getIcon());
        setCaption(Labels.getLabel("system.menu."+view.getViewName()+".caption"));
        ApplicationEventBus.register(this);
        addClickListener(new ClickListener() {
          private static final long serialVersionUID = 7980836676713987476L;

          @Override
          public void buttonClick(final ClickEvent event) {
            UI.getCurrent().getNavigator().navigateTo(view.getViewName());
          }
        });

      }

      @Subscribe
      public void postViewChange(final PostViewChangeEvent event) {
        removeStyleName(STYLE_SELECTED);
        if (event.getView() == view) {
          addStyleName(STYLE_SELECTED);
        }
      }
    }
  }
}

For MainView (I don’t know if ou have the same problem in ResidentView), you cannot use @autowired bean in your constructor (it’s not yet autowired).

You can use final on your autowired bean:

@Autowired
private final ResidentialService residentialService;

And add this as an argument of your constructor (or you can use it on a @PostConstruct method)

Here an explanation:
https://www.petrikainulainen.net/software-development/design/why-i-changed-my-mind-about-field-injection/