Как ввести значения в нулевой объект, используя @Autowired в Spring IOC? - PullRequest
0 голосов
/ 20 декабря 2018

Я только начал работать над приложением Spring Rest, в настоящее время я управляю операциями аутентификации, и я хочу просто проверить, используется ли уже введенный адрес электронной почты, проблема в том, что когда его нет, яне могу автоматически передать bean-компонент Пользователь Я получаю исключение NullPointerException.

Я нашел похожие вопросы в SOF, но мой код кажется правильным, пожалуйста, помогите.

Вот мойКод:

Архитектура проекта

enter image description here

User.java:

@Component
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="idUser", scope = User.class)
public class User implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idUser;
    @Column(name = "login", unique = true)
    private String login;
    private String password;
    private String nom;
    private String prenom;
    private String email;
    private long telephone;
    private String statut;
    private int isDeleted;

    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @ManyToOne(fetch = FetchType.LAZY)
    private Role userRole;

    public User(Long idUser, String login, String password, String nom, String prenom, String email,
            long telephone, String statut, int isDeleted, Role userRole) {
        super();
        this.idUser = idUser;
        this.login = login;
        this.password = password;
        this.nom = nom;
        this.prenom = prenom;
        this.email = email;
        this.telephone = telephone;
        this.statut = statut;
        this.isDeleted = isDeleted;
        this.userRole = userRole;
    }

    public User() {
        super();
    }

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

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

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public long getTelephone() {
        return telephone;
    }

    public void setTelephone(long telephone) {
        this.telephone = telephone;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }

    public int getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(int isDeleted) {
        this.isDeleted = isDeleted;
    }

    public Role getUserRole() {
        return userRole;
    }

    public void setUserRole(Role userRole) {
        this.userRole = userRole;
    }}

UserRepository.java:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    User findByLoginLikeAndPasswordLikeAndIsDeletedEquals(String login, String password, int i);

    User findByLoginLike(String login);
    }

UserDTO.java

@Component
public class UserDTO {

    private Long idUser;

    private String login;
    private String password;

    private String role ;

    public UserDTO(Long idUser, String login, String password, String role) {
        super();
        this.idUser = idUser;
        this.login = login;
        this.password = password;
        this.role = role;
    }

    public UserDTO() {
        super();
    }

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

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

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    } 

}

UserService.java:

@Service
public class UserService {


    @Autowired
    private UserDTO userDto;

    @Autowired
    private User user;


    @Autowired
    private UserRepository userRep;

    @Autowired
    private RoleRepository roleRep;




    public boolean addUser(String login, String password, String role) {
        boolean state = false;


        try {
            System.out.println(user.toString());
            user = userRep.findByLoginLike(login);

            if (user == null) {

                user.setPassword(password);
                user.setLogin(login);               
                user.setUserRole(roleRep.findByNomRoleLike(role));
                userRep.save(user);

                state = true;

            } else {
                System.out.println("user already exists");
                state = false;
            }
        } catch (Exception e) {

            e.printStackTrace();
            state = false;
        }

        return state;
    }

UserController.java

@RestController
public class UserControler {



    @Autowired
    private User user;

    @Autowired
    private UserRepository userRep;

    @Autowired
    private List<User> allUsers;


    @Autowired
    private UserService userService;

    @Autowired
    private UserDTO userDTO;


    @RequestMapping( value = "/addUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Boolean addUser(@RequestBody UserDTO u){
        boolean state = false;
        try {
            state = userService.addUser(u.getLogin(), u.getPassword(), "Administrateur");
        } catch (Exception e) {

            e.printStackTrace();
        }

        return state;
    }

StackTrace:

Hibernate: выберите users0_.user_role_id_role в качестве user_ro10_1_0_,users0_.id_user как id_user1_1_0_, users0_.id_user как id_user1_1_1_, users0_.email как email2_1_1_, users0_.is_ удалено как is_delet3_1_1_, users0_.login в качестве login4_1_1_, users0_.nom в качестве nom5_1_1_, users0_.password в качестве пароля6_1_1_, users0_.prenom в качестве prenom7_1_1_, users0_.statut в качестве statut8_1_1_, users0_.telephone в качестве telephon9_1____________________________________ддддок________ как вы2018-12-20 14: 25: 58.061 TRACE 6192 --- [nio-8080-exec-5] ohtype.descriptor.sql.BasicBinder: параметр привязки 1 как [BIGINT] - [3] 2018-12-20 14: 26: 36.015 WARN 6192 --- [nio-8080-exec-7] .wsmsDefaultHandlerExceptionResolver: Устраненное исключение, вызванное выполнением обработчика: org.springframework.web.HttpRequestMethodNotSupportedException: метод запроса «POST» не поддерживается

java.lang.NullPointerException в

com.akkaprofil.service.UserService.addUser (UserService.java:63) в com.akkaprofil.controller.UserControler.addUser (UserControler).java: 46) в sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke (неизвестный источник) в sun.reflect.DelegatingMethodAccessorImpl.invoke (неизвестный источник) в java.invoke (Неизвестный источник) в org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (InvocableHandlerMethod.java:205) в org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest (InvocableHandlerMethod.java:133) в org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHnog.weg.web.weg.tgRequestMappingHandlerAdapter.invokeHandlerMethod (RequestMappingHandlerAdapter.java:849) в org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdhoho.Hetler.gtg.meg.tb)дескриптор (AbstractHandlerMethodAdapter.java:85) в org.springframework.web.servlet.DispatcherServlet.doDispatch (DispatcherServlet.java:967) в org.springframework.web.servlet.DispatcherServlet.doService.prv (at) (at) (or)).web.servlet.FrameworkServlet.processRequest (FrameworkServlet.java:970) в org.springframework.web.servlet.FrameworkServlet.doPost (FrameworkServlet.java:872) в javax.servlet.http.HttpServlet.service (HttpServlet.java:661) в org.springframework.web.servlet.FrameworkServlet.service (FrameworkServlet.java:846) в javax.servlet.http.HttpServlet.service (HttpServlet.java.7g: 7).catalina.core..java: 52) вorg.apache.catalina.core.RequestContextFilter.java:99) по адресу org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) по адресу org.apache.catalina.core.ApplicationFilterChain.internalDoFilter: atFilter (applicationFilter): atF.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) по адресу org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal (HttpPutFormContentFilter.jworkest.Flayer OnceReFterFraterFerterFrater)) в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) в org.springРаботаJava: 193) в org.apache.catalina.core..OncePerRequestFilter.org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:198) в org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:96) в org.apache.catatorAutheat.ause.invoke (AuthenticatorBase.java:493) в org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:140) в org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.g).apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:87) при org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:342) в org.apache.coyote.http11.Http11Processor.service (Http11Processor.java: 800) в org.apache.coyote.AbstractProcessorLight.process (AbstractProcessorLight.java:66) в org.apache.coyote.AbstractProtocol $ ConnectionHandler.process (AbstractProtocol.java:806) в org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun (NioEndpoint.java:1498) в org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java:49) в java.util.concurrent.ThreadPoolExecutor.runWorker ()java.util.concurrent.ThreadPoolExecutor $ Worker.run (неизвестный источник) по адресу org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run (TaskThread.java: 61) at java.lang.Thread.run (неизвестный источник)

Когда я вызываю метод запроса AddUser, это исключение срабатывает, я не могу найти причину, почему значения не являютсяустановите для объекта Object, когда адрес электронной почты не найден, Все классы аннотированы с их стереотипами, пользователь Бин имеет автоматическую привязку, я не объявил нового оператора.

БудетВы разъясняете причину этого исключения.Спасибо

...