Vaadin14 BeanCreationException: during trying to call save method of my ser

Hi I have a little Vaadin project. In there, I’ve a UserUtils.class which has a createNewUser method which looks like this:

LoginView:

import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;

import static com.packagename.utils.UserUtils.createNewUser;

@Route("login")
@PageTitle("Login - packagename")

public class LoginView extends VerticalLayout implements BeforeEnterObserver {

    private LoginForm login = new LoginForm();
    private PasswordEncoder passwordEncoder;

    public LoginView(){
        createNewUser("daniel.tran", "cAWFCMaa22", true, "ADMIN");
        addClassName("login-view");
        setSizeFull();
        setAlignItems(Alignment.CENTER);
        setJustifyContentMode(JustifyContentMode.CENTER);

        login.setAction("login");

        add(
                new H1("Willkommen!"),
                login
        );
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // Inform the user about an authentication error
        if (!event.getLocation()
                .getQueryParameters()
                .getParameters()
                .getOrDefault("error", Collections.emptyList())
                .isEmpty()) {
            login.setError(true);
        }
    }
}

UserUtils.class:

import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.service.UserService;
import com.packagename.security.SecurityConfiguration;
import com.packagename.ui.views.login.LoginView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

public class UserUtils {

    @Autowired
    private LoginView loginView;
    private static UserService userService;
    private PasswordEncoder passwordEncoder;

    public static void createNewUser(String pUsername, String pPassword, boolean pStatus, String pRole) {

        if (!UserUtils.userExists(pUsername)) {
            userService = new UserService();
            PasswordEncoder passwordEncoder = SecurityConfiguration.passwordEncoder();
            String encodedPassword = passwordEncoder.encode(pPassword);
            UserEntity user = new UserEntity();
            user.setUserName(pUsername);
            user.setPassword(encodedPassword);
            user.setStatus(pStatus);
            user.setRoles(pRole);
            userService.save(user);
        }
    }

    private static boolean userExists(String pUsername) {
        userService = new UserService();
        UserEntity user = new UserEntity();
        user.setUserName(pUsername);
        boolean exists = userService.exists(user);
        return exists;
    }
}

UserService.class:

import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

@Service
public class UserService {

    private UserRepository userRepository;
    private Logger LOGGER;

    @Autowired
    public UserService(UserRepository pUserRepository) {
        this.userRepository = pUserRepository;
    }

    public UserService() {}

    public List<UserEntity> findAll() {
        return userRepository.findAll();
    }

    public long count() {
        return userRepository.count();
    }

    public void delete(UserEntity user) {
        userRepository.delete(user);
    }

    public void save(UserEntity user) {
        if (user == null) {
            LOGGER.log(Level.SEVERE, "Contact is null. Are you sure you have connected your form to the application?");
            return;
        }
        userRepository.save(user);
    }

    public boolean exists(UserEntity user) {
        Example<UserEntity> example = Example.of(user);
        boolean exists = userRepository.exists(example);
        return exists;
    }
}

UserEntity.class:

import javax.persistence.*;

@Entity
@Table(name = "PSYS_USERS")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userid;
    private String userName;
    private String password;
    private boolean status;
    private String roles;

    public UserEntity(){}

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String getRoles() {
        return roles;
    }

    public void setRoles(String roles) {
        this.roles = roles;
    }
}

UserRepository.class

import com.packagename.backend.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository<UserEntity, Integer> {
    Optional<UserEntity> findByUserName(String userName);
}

And always when it comes to the situtation, trying to call the userService methods, then it throws the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.packagename.ui.views.login.LoginView': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.packagename.ui.views.login.LoginView]
: Constructor threw exception; nested exception is java.lang.NullPointerException

I tried to create a default constructor, at the entity and also at the service class but nothing want help.

So far,
Daniel

Without analyzing the code deeply, I think your problem might be that you’re using static methods together with autowiring. Try removing all static keywords from UserUtils and rewriting your code based on that. Do you even really need a UserUtils instead of having a similar method in UserService? Also, a simple rule of thumb to follow: you should never initialize a Spring Component or Service with the new keyword (unless you’re doing it in a @Configuration class).

Dear Olli,

thanks for replying that fast and also for your advices. Forgive me my unexperience, I am very new to Vaadin/Spring/Web development in Java. Therefore I am very thankful for every advice from a more experienced developer.

I now have applied your advices and removed als static keywords and put the both methods into the UserService.class, but it now marks me an error at the userExists method:

boolean exists = userRepository.exists(user);

In summary my changed classes looks now like this:

LoginView.class:

package com.packagename.ui.views.login;

import com.packagename.backend.service.UserService;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;

@Route("login")
@PageTitle("Login - packagename")

public class LoginView extends VerticalLayout implements BeforeEnterObserver {

    private LoginForm login = new LoginForm();
    private UserService userService;
    private PasswordEncoder passwordEncoder;

    public LoginView(){
        userService.createNewUser("daniel.tran", "cAWFCMaa22", true, "ADMIN");
        addClassName("login-view");
        setSizeFull();
        setAlignItems(Alignment.CENTER);
        setJustifyContentMode(JustifyContentMode.CENTER);

        login.setAction("login");

        add(
                new H1("Willkommen!"),
                login
        );
    }


    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // Inform the user about an authentication error
        if (!event.getLocation()
                .getQueryParameters()
                .getParameters()
                .getOrDefault("error", Collections.emptyList())
                .isEmpty()) {
            login.setError(true);
        }
    }
}

UserService.class:

package com.packagename.backend.service;

import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.repository.UserRepository;
import com.packagename.security.SecurityConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

@Service
public class UserService {

    private UserRepository userRepository;
    private Logger LOGGER;

    @Autowired
    public UserService(UserRepository pUserRepository) {
        this.userRepository = pUserRepository;
    }

    public UserService() {}

    public List<UserEntity> findAll() {
        return userRepository.findAll();
    }

    public long count() {
        return userRepository.count();
    }

    public void delete(UserEntity user) {
        userRepository.delete(user);
    }

    public void save(UserEntity user) {
        if (user == null) {
            LOGGER.log(Level.SEVERE, "Contact is null. Are you sure you have connected your form to the application?");
            return;
        }
        userRepository.save(user);
    }

    public boolean exists(UserEntity user) {
        Example<UserEntity> example = Example.of(user);
        boolean exists = userRepository.exists(example);
        return exists;
    }

    public void createNewUser(String pUsername, String pPassword, boolean pStatus, String pRole) {
        if (!userExists(pUsername)) {
            PasswordEncoder passwordEncoder = SecurityConfiguration.passwordEncoder();
            String encodedPassword = passwordEncoder.encode(pPassword);
            UserEntity user = new UserEntity();
            user.setUserName(pUsername);
            user.setPassword(encodedPassword);
            user.setStatus(pStatus);
            user.setRoles(pRole);
            userRepository.save(user);
        }
    }

    public boolean userExists(String pUsername) {
        UserEntity user = new UserEntity();
        user.setUserName(pUsername);
        boolean exists = userRepository.exists(user);
        return exists;
    }
}

Do you know why? Again thank you very much for your fast reply. :slight_smile:

So far,
Daniel

At least in LoginView, you should autowire UserService.