服务类Spring引导中的空指针异常[重复]

Posted

技术标签:

【中文标题】服务类Spring引导中的空指针异常[重复]【英文标题】:Null pointer Exception in Service class Spring boot [duplicate] 【发布时间】:2019-03-10 20:42:58 【问题描述】:

Good Day.. 我正在尝试创建一个 Spring Boot Web 应用程序,我必须在其中找到 Spring Boot 的用户详细信息中的用户,但在使用测试时出现错误,这是我的配置:

用户类别:

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "USERS")
public class User implements Serializable 

  /**
     * 
     */
    private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy= GenerationType.IDENTITY)
  @Column(name = "USERNAME")
  private String username;

  @Column(name = "PASSWORD", nullable = false)
  private String password;

  @Column(name = "ENABLED", nullable = false)
  private boolean enabled;

  public User() 
    super();
    // TODO Auto-generated constructor stub


public User(String username, String password, boolean enabled, Set<Authorities> authorities, Customer customer) 
    super();
    this.username = username;
    this.password = password;
    this.enabled = enabled;
    this.authorities = authorities;
    this.customer = customer;


@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
  private Set<Authorities> authorities = new HashSet<>();

  @OneToOne(cascade = CascadeType.ALL)
    private Customer customer;
  //Getter and Setter methods

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 isEnabled() 
    return enabled;


public void setEnabled(boolean enabled) 
    this.enabled = enabled;


public Set<Authorities> getAuthorities() 
    return authorities;


public void setAuthorities(Set<Authorities> authorities) 
    this.authorities = authorities;


public Customer getCustomer() 
    return customer;


public void setCustomer(Customer customer) 
    this.customer = customer;



用户存储库:

package com.vishal.project.repos;
import com.vishal.project.entities.User;
public interface UserRepository extends CrudRepository<User,Long> 

    User findUserByUsername(String username);


UserDetailsS​​erviceImpl.class

package com.vishal.project.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vishal.project.entities.User;

import com.vishal.project.repos.UserRepository;



@Service("UserService")
public class UserDetailsServiceImpl implements UserDetailsService 

  @Autowired
  private UserRepository userRepo;

  @Transactional(readOnly = true)
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 

    User user = userRepo.findUserByUsername(username);
    UserBuilder builder = null;
    if (user != null) 

      builder = org.springframework.security.core.userdetails.User.withUsername(username);
      builder.disabled(!user.isEnabled());
      builder.password(user.getPassword());
      String[] authorities = user.getAuthorities()
          .stream().map(a -> a.getAuthority()).toArray(String[]::new);

      builder.authorities(authorities);
     else 
      throw new UsernameNotFoundException("User not found.");
    
    return builder.build();
  

  public User save(User user) 
      return userRepo.save(user);
  



所以我正在运行测试,例如: 用户详情测试:

package com.vishal.project;

import static org.junit.Assert.assertNotNull;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

import org.springframework.security.core.userdetails.UserDetailsService;

import com.vishal.project.entities.User;
import com.vishal.project.services.UserService;



public class UserDetailsTest 

    private static Logger logger = LoggerFactory.getLogger(UserDetailsTest.class);

    private GenericApplicationContext ctx;
    private UserDetailsService userDetailsService;
    private UserService userService;

    @Before
    public void SetUp() 
        ctx = new AnnotationConfigApplicationContext(OnlineBookShoppeApplication.class);
        userDetailsService = ctx.getBean(UserDetailsService.class);
        logger.info("starting to run tests now............");
        assertNotNull(userDetailsService);
       
        @Test
        public void testfindByUsername() 
             User user = userService.findByUsername("admin");
             String Username = user.getUsername();
             logger.info("Username=" + Username);

        

        @After
         public void teardown() 
            ctx.close();
        

    

但是得到一个错误例如:

java.lang.NullPointerException
    at com.vishal.project.UserDetailsTest.testfindByUsername(UserDetailsTest.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

用户服务接口:

package com.vishal.project.services;

import com.vishal.project.entities.User;

public interface UserService 

    User findByUsername(String username);
    User save (User user);


我们将不胜感激...

【问题讨论】:

UserDetailsTest.java:37 是哪一行? userService 为 null 或 user 为 null 【参考方案1】:

您的userService 字段是null,因为您尚未为其分配值。您的测试似乎没有使用您的 userDetailsService 字段,因此您可以删除它然后替换此行:

userDetailsService = ctx.getBean(UserDetailsService.class);

有了这个:

userService = ctx.getBean(UserService.class);

【讨论】:

谢谢先生。现在我收到这个错误它说没有 quaorg.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.vishal.project.services.UserService' available 但我已经为 UserService 定义了 UserdetailsS​​erviceImpl。刚刚将服务方法添加到问题中

以上是关于服务类Spring引导中的空指针异常[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Spring 代理类和 Kotlin 中的空指针异常

使用 Spring Boot 服务作为批处理作业中的依赖项的空指针异常

如何解决spring boot test中的空指针异常?

Spring MVC 项目中的空指针异常

Hibernate Interceptor 中自动装配字段的空指针异常(类由 Spring 管理)

操作栏中的空指针异常[重复]