CDI @Inject in View does not work

Hi

Details:

  • I have a new vaadin project using latest 7.3 with CDI plugin
  • @Inject works properly on Main UI class
  • I am injecting an EJB with Stateless, LocalBean

Problem:

  • Tried to transfer the same EJB and EJB call on a View class but bean is throwing null pointer when being accessed.
@SuppressWarnings("serial")
@CDIView(value = CityView.VIEW_ID)
public class CityView extends Panel implements View {
    
    public static final String VIEW_ID = "city";
        
    @Inject
    private CityBean cityBean;

I’ve mostly seen the documentation but it just covers the UI class using the CDI. Also what is the difference of ClassBasedViewProvider and CDIViewProvider, does this have any effect on my current problem

Hey, I’d guess that your View bean is not managed rendering the CDI injection mechanism inoperable. The difference between CDIViewProvider and ClassBasedViewProvider is that CDIViewProvider is able to instantiate views as CDI managed beans.

With CDI you don’t need to register the views but instead you build your Navigator the following way:

@Inject
private CDIViewProvider viewProvider;

...

Navigator navigator = new Navigator(UI, componentContainer);
navigator.addProvider(viewProvider);

After this you’re able to navigate to a view of your choosing so that Navigator will instantiate (and or find the existing instance from context).

Always make sure that your “injection chain” is complete as otherwise nothing will process the injection annotations if you’re just working with standard pojo.

In short, make sure your view is really a managed CDI bean. You can do this with CDIViewProvider in navigator. Do not register the view manually as then it’s a regular pojo not a CDI bean.

Hope the above helps! Let me know if you have more problem.

Hi Peter,

Thanks for the advice. But I’m just starting out vaadin so a couple more questions since you mentioned the components would just be standard pojos and “injection chain”.

I’ll show you below the different classes I’m using and how I can chain them together. The structure is somewhat based to the Vaadin DashboardDemo.

Main UI

[code]
@CDIUI(“”)
public class WallOfLoveUI extends UI {

@Override
protected void init(VaadinRequest request) {
    setContent(new MainView());
}

}
[/code]MainView

[code]
@SuppressWarnings(“serial”)
public class MainView extends HorizontalLayout {

public MainView(){
    setSizeFull();
    addStyleName("mainview");
    
    addComponent(new Menu());
    
    ComponentContainer content = new CssLayout();
    content.addStyleName("view-content");
    content.setSizeFull();
    addComponent(content);
    setExpandRatio(content, 1.0f);
    
    new WallOfLoveNavigator(content);
}

}
[/code]What annotation should I include in this class? Also this is where I call my navigator.

Navigator

What annotation should I Include in navigator class? Also this is where I added the CDIViewProvider. Will the CDIView automatically be picked up by the CDIViewProvider? Also is this the right way to navigate it to the dashboard view?

[code]
@SuppressWarnings(“serial”)
public class WallOfLoveNavigator extends Navigator {

@Inject
private CDIViewProvider viewProvider;

public WallOfLoveNavigator(ComponentContainer container){
    super(UI.getCurrent(), container);
    addProvider(viewProvider);
    navigateTo("dashboard")
}

}
[/code]Dashboard
This is where I plan to call my ejb and get some data.

@SuppressWarnings("serial")
@CDIView(value = DashboardView.VIEW_ID)
public class DashboardView extends Panel implements View {
    
    public static final String VIEW_ID = "dashboard";
   
    @Inject
    private CityBean cityBean;
    private TlCitySimple city;

    private Label titleLabel;
    private CssLayout dashboardPanels;
    private VerticalLayout root;
    private Window notificationsWindow;
    
    public DashboardView(){
        addStyleName(ValoTheme.PANEL_BORDERLESS);
        setSizeFull();
        
        root = new VerticalLayout();
        root.setSizeFull();
        root.setMargin(true);
        root.addStyleName("dashboard-view");
        setContent(root);
        Responsive.makeResponsive(root);

        root.addComponent(buildHeader());

        root.addLayoutClickListener(new LayoutClickListener() {
            @Override
            public void layoutClick(LayoutClickEvent event) {
                //DashboardEventBus.post(new CloseOpenWindowsEvent());
            }
        });
    }
    
    private Component buildHeader() {
        HorizontalLayout header = new HorizontalLayout();
        header.addStyleName("viewheader");
        header.setSpacing(true);

        city = cityBean.getModelByPk(5000);
        System.out.println(city.getName());
      
        titleLabel = new Label("Dashboard");
        titleLabel.setSizeUndefined();
        titleLabel.addStyleName(ValoTheme.LABEL_H1);
        titleLabel.addStyleName(ValoTheme.LABEL_NO_MARGIN);
        header.addComponent(titleLabel);

        return header;
    }
    
    @Override
    public void enter(ViewChangeEvent event) {
    }

}

I hope you guys can give me more advice to chain and properly make this simple lesson work out! Cheers!

Hey again,

I think I spotted few problems in the code:

  1. You’re creating your navigator with keyword ‘new’. This indicates that you’re creating a regular object that is not CDI managed bean. This will lead the @Inject in your navigator not being processed leaving the CDIViewProvider to be null.

You should change this to something more like this:

[code]
@CDIUI(“”)
public class WallOfLoveUI extends UI {

@Inject   
private CDIViewProvider viewProvider;

private Navigator navigator;

@Override
protected void init(VaadinRequest request) {
    MainView mainView = new MainView();
    setContent(mainView);
    navigator = new WallOfLoveNavigator(this, mainView);
    navigator.addProvider(viewProvider);
}

}
[/code]It’s not necessary to inject navigator it self and this can even be little difficult in some circumstances as Navigator needs to have a super constructor that sets the UI and view content. That’s why it’s recommended to have Navigator as is and just pass the CDIViewProvider through the addProvider method. It’s important though that you @Inject the CDIViewProvider because it’s also a managed CDI bean meaning that CDIViewProvider will only work if it’s part of the “injection chain”. See the above code.

After you have marked your dashboard view with @CDIView(“dashboard”) it’s available for navigation through CDIViewProvider. This means that if you call navigator.navigateTo(“dashboard”) what really happens behind the scenes is that CDIViewProvider will look up a view bean with corresponding name in annotation and inject this for you. This is also the reason why you then can use @EJB or @Inject in your view as also the view is now part of the CDI injection chain.

Here’s a little example what you could do to make basics works:

UI:

@CDIUI("")
public class MyUI extends UI {

    @Inject   
    private CDIViewProvider viewProvider;

    private Navigator navigator;

    @Override
    protected void init(VaadinRequest request) {
        MainView mainView = new MainView();

        navigator = new Navigator(this, mainView);
        navigator.addProvider(viewProvider);

        setContent(mainView);

        navigator.navigateTo(“dashboard”);
    }
}

View:

@CDIView(“dashboard”)
public class DashboardView extends VerticalLayout implements View {

   @Inject // (or @EJB in case the resource is really an EJB)
   private SomeBackendServiceEJB backendService;

   public DashboardView() {
     //Do some regular pojo based Vaadin layout operations here.
     //Notice that backendService is not yet injected here.
   }

   @PostConstruct
   protected void initialize() {
       // @PostConstruct method is invoked by the CDI container when injections are done
       backendService.someMethod(); … // You're now free to invoke backendService as it's guaranteed to be injected at this point.
   }
}

In general, few best practices:

  1. Don’t inject navigator
  2. It’s usually not necessary to extend navigator but if there’s some special logic you need there you can do it
  3. Always @Inject CDIViewProvider
  4. Add the injected CDIViewProvider to navigator with addProvider method
  5. Annotate your view class with @CDIView(“my-view-name”) and implement the Navigator’s View interface to make it navigator compatible.

(6) You should never have to @Inject your view directly but always get the instance through navigator. It is possible to get an instance of the view by injecting the specific view bean but currently this works best only with so called “normal scoped beans” which are not enabled by default. If you still need to do this at some point you can annotate your view with @NormalViewScoped annotation. For now with your example you don’t need it.

Also, always remember that injections only works inside beans which are managed. They work inside your Vaadin UI because Vaadin UI is a managed bean when using Vaadin-CDI addon.

If you use keyword ‘new’ this will “break” the injection chain as then your code is managing the object, not the CDI context. That’s why it’s important always to @Inject the required resources. And finally, this is exactly same principle with for example Spring Beans and @Autowired and also used in other DI frameworks.

Hi again Peter

Thank’s I’ve managed to inject the bean properly now but I can only access it in the @Postconstruct method, but is there a way I can access those in the constructor? I tried putting the result on a variable and access it in the constructor but It doesn’t get set.

Also when do I use @UIScoped?

@CDIView(“dashboard”)
public class DashboardView extends VerticalLayout implements View {
   @EJB
   private CityBean cityBean;

   private City city;

   public DashboardView() {
       System.out.println(city.getName());
   }
   @PostConstruct
   protected void initialize() {
       city = cityBean.getModelByPk(new Long(1));
   }
}

Hey, glad to hear!

You can access the bean in constructor only if you define a constructor injection. It’s for example something like this:

[code]
public class MyBean {

@Inject
public MyBean(SomeOtherBean bean) {
    bean.someMethod();
}


}
[/code]In the above case you still need to inject the MyBean like this:

@Inject
private MyBean bean;

CDI would invoke the particular constructor with @Inject annotation and find correspondinging SomeOtherBean from the current context.

@UIScoped (and @ViewScoped) are context definitions which mean that everything you have in UI scope or View scope is always “dependent” on the specific UI or View instance. This is: as long as you are inside the same Vaadin UI instance defined with @CDIUI or @CDIView (@CDIUI and @CDIView are automatically @UIScoped and @ViewScoped respectively) , the same instance of your @UIScoped beans gets injected always. If you switch to another UI it will have it’s own specific instance of the UI scoped bean. ViewScoped works similarly but just with more fine grained view context.

You can think UIScope and ViewScope as pools of object. Each UI and View instance have their own pool from which the injected bean is referenced. This simply means that if you define your own bean with @UIScoped and inject it into a UI (or some other bean that is inside the same context) the same instance of your bean gets injected because all beans which belong to same @UIScoped context share the same objects. This is a powerful mechanism that makes it possible to acquire instance to same object without having to drag the references along.

Let’s say you make a UI that has some parts that you want to keep common for all the views, for example a ‘header’ or ‘footer’ component or some menu for example, you could @UIScoped those components. @UIScoped header or footer component simply means that the bean would be the same instance inside this UI, no matter where you inject it. If you open another UI instance (by opening a new tab for example) a new instance of @UIScoped header or footer would be injected. This is because each UI have their own pool of objects (context) from which the injected object is referenced.

Hope this helps. All the above by the way has nothing specific to do with Vaadin. Only thing that comes from Vaadin (from Vaadin-CDI addon more specificly) is the definition of @UISCope and @ViewScope but the whole scoping paradigm is purely CDI.

Thanks for the great explanation :slight_smile:

I created a datatable-component, that includes a view, which should not be managed by the CDIViewProvider. The component can later be added to different views in my application. So far everything works.
Now I’ve injected a message handler, that provides string properties from a messages.properties file.

[code]
public class MarktViewImpl extends VerticalLayout {

private static final long serialVersionUID = -7255122903510040616L;

@Inject
private Messages messages;

private Grid grid;

public MarktViewImpl() {
    this.setSizeUndefined();
    this.setMargin(true);
    this.setSpacing(true);
    this.buildUI();
    this.initUI();
}

private void buildUI() {
    grid = new Grid(messages.get("marktGrid.title"));
    
    this.addComponent(grid);        
}

...

[/code]I get a Nullpointer Exception when it tries to access the get method on messages. Do I have to annotate the view with @CDIVIEW to make it managable by the CDIViewProvider and to make the injection work, even if I don’t want the view be accessable by the navigator? Or is there any other way? Thanks for your suggestions.

Hey Dirk, how are you using your MarktViewImpl? Are you injecting it with @Inject? If you’re creating it with just new keyword injections won’t work inside of it as then the MarktViewImpl is not a managed bean. If you intend to use your MarktViewImpl with other views as a component I would suggest you annotate it with @ViewScoped so that each view will get its own instance of it. Inside the view (which is a managed bean, implements View interface and has @CDIView annotation) you can then @Inject the MarktViewImpl. Only then the injections inside of it will work. Hope this helps.

  • Peter

Hi Peter,

Currently I use a “Humble View”, so I do have a MarktViewImpl and a MarktViewImplLogic, which references the MarktViewImpl as follows:

[code]
public class MarktViewImplLogic implements MarktView {

private final MarktViewImpl view;
private BeanItemContainer<MarktItem> container = new BeanItemContainer<MarktItem>(MarktItem.class);

@Inject
private Messages messages;

@Inject
public MarktViewImplLogic(MarktViewImpl view) {
    if (view == null) {
        throw new NullPointerException("Undefined View!");
    }
    this.view = view;
    this.bindDataSource();
    this.initGrid();
    this.setupFilter();
    this.registerListeners();    
}

private void initGrid() {
    Grid grid = this.view.getGrid();
    grid.setCaption(messages.get("marktGrid.title"));

...

[/code]I have moved the injection of the message bean to MarktViewImplLogic, but injection doesn’t work here as well.

I have a MarktComponentImpl, which acts as the presenter. MarktViewImplLogic, which represents the view to the presenter is referenced there as follows:

[code]
public class MarktComponentImpl extends AbstractPresenter<MarktModel, MarktView> implements MarktComponent {

@Inject
public MarktKzComponentImpl(MarktKzModel model, MarktKzView view) {
    super(model, view);
}

[/code]Finally I do have a View, which implements the View interface and is annotated with @CDIView.

[code]
@CDIView(“”)
public class DashboardView extends VerticalLayout implements View {

public static final String NAME = "";

@Inject
private MarktComponent marktView;

public DashboardView() {
    setMargin(true);
    setSizeFull();
}

@PostConstruct
public void init() {
    Component marktViewComponent = marktView.getViewAs(Component.class);
    this.addComponent(marktViewComponent);
}

[/code]Without the injection of the message bean everything works fine. Injection of the message bean in my MainUI works as well.

Thanks for your help

Dirk

Hi, I have problem with CDI Injection and I read all the post above and still cannot figure out where the problem is.

Can someone help if you had the same problem?

vaadin 7.6.4, javaee-web-api 7.0, vaadi-cdi 1.0.3, cdi-helpers 1.12
Server Wildfly 9.0.2 final

Here is my Error message
[size=1]

NFO - UIScopedContext registered for Vaadin CDI
DEBUG - Instantiating ViewScoped context
INFO - ViewScopedContext registered for Vaadin CDI
15:01:14,896 ERROR [org.jboss.msc.service.fail]
 (MSC service thread 1-7) MSC000001: Failed to start service jboss.deployment.unit."calendar_hibernate.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."calendar_hibernate.war".WeldStartService: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type StaffDAO with qualifiers @Default
  at injection point [BackedAnnotatedField]
 @Inject @Default com.calendar.backend.calendar_hibernate.view.MainView.staffDAO
  at com.calendar.backend.calendar_hibernate.view.MainView.staffDAO(MainView.java:0)

    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:359)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:281)
    at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:155)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:518)
    at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
    at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    ... 3 more

15:01:14,901 ERROR [org.jboss.as.controller.management-operation]
 (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "calendar_hibernate.war")]
) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"calendar_hibernate.war\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"calendar_hibernate.war\".WeldStartService: Failed to start service
    Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type StaffDAO with qualifiers @Default
  at injection point [BackedAnnotatedField]
 @Inject @Default com.calendar.backend.calendar_hibernate.view.MainView.staffDAO
  at com.calendar.backend.calendar_hibernate.view.MainView.staffDAO(MainView.java:0)


UI Class

@Theme("mytheme")
@CDIUI("")
@SuppressWarnings("serial")
public class MyUI extends UI {
    

    @Inject
    CDIViewProvider viewProvider;
    
    @Override
    protected void init(VaadinRequest vaadinRequest) {

        Navigator navigator = new Navigator(this, this);
        navigator.addProvider(viewProvider);
        navigator.navigateTo(LoginView.LOGIN);

    }

}

[/size]

[size=1]

My Class MainView Class

@CDIView("MAINVIEW")
public class MainView extends MainMenuNavLayoutDesign implements View {

    public static final String VIEWNAME="MAINVIEW";
    
    @Inject @Default
    StaffDAO staffDAO;
    
    public MainView() {
        
        MyCommand command = new MyCommand();
        menuBar.setCommand(command);
        menuBar.setStyleName("user-menu");
        menuBar.setImmediate(true);
        
    }
    
    @PostConstruct
    public void PostConstruct(){
        
        leftVerticalLayout.removeAllComponents();
        MGrid<AdminStaff> grid = new MGrid<AdminStaff>(AdminStaff.class).withProperties("firstName","lastName","userName");
        BeanItemContainer<AdminStaff> bItemContainer = new BeanItemContainer<AdminStaff>(AdminStaff.class);
        bItemContainer.addAll(staffDAO.findAllAdminStaff());
        grid.setContainerDataSource(bItemContainer);
        
        leftVerticalLayout.addComponent(grid);
        
    }

    @Override
    public void enter(ViewChangeEvent event) {
        
        Staff staff;
        
        if((staff=(Staff) UI.getCurrent().getSession().getAttribute("STAFF"))!=null){
            user_name_label.setValue(staff.getFirstName()+" "+staff.getLastName());
            user_name_label.setImmediate(true);
        }

    }
    
    public class MyCommand implements MenuBar.Command{

        @Override
        public void menuSelected(MenuItem selectedItem) {
            
            if(selectedItem.getText().equals("Company Info")){

                if(leftVerticalLayout.getComponentCount()!=0)
                        leftVerticalLayout.removeAllComponents();
                
                leftVerticalLayout.addComponent(new NewAccountView());
                leftVerticalLayout.setVisible(true);
                
                if(rightVerticalLayout.getComponentCount()!=0)
                    rightVerticalLayout.removeAllComponents();
                
                    rightVerticalLayout.addComponent(new AccountInfoView());
                    rightVerticalLayout.setVisible(true);
                
            }else if(selectedItem.getText().equals("Add Staff")){
                
                if(leftVerticalLayout.getComponentCount()!=0)
                    leftVerticalLayout.removeAllComponents();
            
                leftVerticalLayout.addComponent(new NewStaffView());
                leftVerticalLayout.setVisible(true);
                
            }
            
        }
        
    }
class MainViewPresenter{
    
}

}
[/size]

[size=1]

Staff DAO and IMP class

public interface StaffDAO {

    public Staff findUserWithUserNamePassword(StaffCredential credential);
    
    public List<AdminStaff> findAllAdminStaff();
    
}


package com.calendar.backend.calendar_hibernate.view.dataservice;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.inject.Default;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

import com.calendar.backend.calendar_hibernate.entityUtility.CreateJDBCTransation;
import com.vaadin.cdi.ViewScoped;

@ViewScoped
@Default
public class StaffImp implements StaffDAO , Serializable {

    
    @Override
    public Staff findUserWithUserNamePassword(StaffCredential credential) {
        
        CreateJDBCTransation transation = new CreateJDBCTransation();
        transation.getTransaction().begin();
        
        CriteriaBuilder cbBuilder = transation.getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Staff> criteriaQuery = cbBuilder.createQuery(Staff.class);
        
        Root<Staff> root = criteriaQuery.from(Staff.class);
        
        Path<StaffCredential> staffCredential = root.get("credentail");
        
        criteriaQuery.select(root).where(cbBuilder.equal(staffCredential,credential));
        
        TypedQuery<Staff> query = transation.getEntityManager().createQuery(criteriaQuery);
        
        return query.getResultList().get(0);
        
    }

    @Override
    public List<AdminStaff> findAllAdminStaff() {
        
        CreateJDBCTransation transation = new CreateJDBCTransation();
        transation.getTransaction().begin();
        
        CriteriaBuilder cBuilder = transation.getEntityManager().getCriteriaBuilder();
        CriteriaQuery<AdminStaff> cQuery = cBuilder.createQuery(AdminStaff.class);
        
        Root<AdminStaff> root = cQuery.from(AdminStaff.class);
        
        TypedQuery<AdminStaff> query = transation.getEntityManager().createQuery(cQuery);
        
        return query.getResultList();
        
    }

}

[/size]

I have solve the problem that cause the bug, Maybe someone with more experience can explain it in more detail.
Thanks.

  1. I put @Local of my SaffDAO , and @Stateless of StaffIMP

  2. Put MainViewPresenter into a separted class rather a inner class

  3. Put @Sessionscope of MainViewPresenter
    4 Put
    @EJB
    StaffDAO staffDAO[code]
    @Local
    public interface StaffDAO {

    public Staff findUserWithUserNamePassword(StaffCredential credential);

    public List findAllStaff();

}

@Stateless
public class StaffImp implements StaffDAO , Serializable {

@Override
public Staff findUserWithUserNamePassword(StaffCredential credential) {
    
    CreateJDBCTransation transation = new CreateJDBCTransation();
    transation.getTransaction().begin();
    
    CriteriaBuilder cbBuilder = transation.getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Staff> criteriaQuery = cbBuilder.createQuery(Staff.class);
    
    Root<Staff> root = criteriaQuery.from(Staff.class);
    
    Path<StaffCredential> staffCredential = root.get("credentail");
    
    criteriaQuery.select(root).where(cbBuilder.equal(staffCredential,credential));
    
    TypedQuery<Staff> query = transation.getEntityManager().createQuery(criteriaQuery);
    
    return query.getResultList().get(0);
    
}

@Override
public List<Staff> findAllStaff() {
    
    CreateJDBCTransation transation = new CreateJDBCTransation();
    transation.getTransaction().begin();
    
    CriteriaBuilder cBuilder = transation.getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Staff> cQuery = cBuilder.createQuery(Staff.class);
    
    Root<Staff> root = cQuery.from(Staff.class);
    
    TypedQuery<Staff> query = transation.getEntityManager().createQuery(cQuery);
    
    return query.getResultList();
    
}

}
[/code][code]
@SessionScoped
public class MainViewPresenter implements Serializable{

@EJB
StaffDAO staffDAO;

List<Staff> findAllStaff(){
    return staffDAO.findAllStaff();
}

}

@CDIView(“MAINVIEW”)
public class MainView extends MainMenuNavLayoutDesign implements View {

public static final String VIEWNAME="MAINVIEW";


@Inject
Instance<MainViewPresenter> presenterInstance;

public MainView() {
    
    MyCommand command = new MyCommand();
    menuBar.setCommand(command);
    menuBar.setStyleName("user-menu");
    menuBar.setImmediate(true);
    
}


@Override
public void enter(ViewChangeEvent event) {
    
    Staff staff;
    
    if((staff=(Staff) UI.getCurrent().getSession().getAttribute("STAFF"))!=null){
        user_name_label.setValue(staff.getFirstName()+" "+staff.getLastName());
        user_name_label.setImmediate(true);
    }
    

}


public class MyCommand implements MenuBar.Command{

    @Override
    public void menuSelected(MenuItem selectedItem) {
        
        if(selectedItem.getText().equals("Company Info")){

            if(leftVerticalLayout.getComponentCount()!=0)
                    leftVerticalLayout.removeAllComponents();
            
            leftVerticalLayout.addComponent(new NewAccountView());
            leftVerticalLayout.setVisible(true);
            
            if(rightVerticalLayout.getComponentCount()!=0)
                rightVerticalLayout.removeAllComponents();
            
                rightVerticalLayout.addComponent(new AccountInfoView());
                rightVerticalLayout.setVisible(true);
            
        }else if(selectedItem.getText().equals("Add Staff")){
            
            if(leftVerticalLayout.getComponentCount()!=0)
                leftVerticalLayout.removeAllComponents();
        
            leftVerticalLayout.addComponent(new NewStaffView());
            leftVerticalLayout.setVisible(true);
            
        }else if(selectedItem.getText().equals("Add Role")){
            Notification.show("Add Role");
            leftVerticalLayout.removeAllComponents();
            MGrid<Staff> grid = new MGrid<Staff>(Staff.class).withProperties("firstName","lastName");
            BeanItemContainer<Staff> bItemContainer = new BeanItemContainer<Staff>(Staff.class);
            bItemContainer.addAll(((MainViewPresenter)presenterInstance.get()).findAllStaff());
            grid.setContainerDataSource(bItemContainer);
            leftVerticalLayout.addComponent(grid);
            leftVerticalLayout.setVisible(true);
        }
        
    }
   }

[/code]