Spring Data存储库无法自动装配

时间:2018-09-24 14:05:51

标签: java spring-boot spring-data repository

我正在从头开始创建一个新的Spring Boot应用程序,并希望为其编写测试。我刚刚在我的应用中实现了身份验证,并想了解角色的工作原理。

当我在身份验证过程中使用UserRepository时,一切都会正常进行。但是,当我想在测试中使用UserRepository时,它说该对象为null,这与在应用程序代码中使用该对象相同。这是为什么? 这是代码。

安全配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PowderizeUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .logout().permitAll();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManager) {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationManager.authenticationProvider(authenticationProvider);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

}

用户类别:

@Entity
@Table(name = "USERS")
@NoArgsConstructor
@Getter
public class User extends BaseEntity {

    private String firstName;
    private String lastName;
    private String emailAddress;
    private String nickname;
    private String password;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private boolean enabled;
    @ManyToMany(mappedBy = "users_roles")
    private Set<Role> roles;
}

存储库:

public interface UserRepository extends CrudRepository<User, Long> {

    public Optional<User> findByEmailAddress(String email);
}

UserDetailsS​​ervice实现类,它使用存储库没有问题:

@Service
public class PowderizeUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
                return new PowderizePrincipal(
                        userRepository.findByEmailAddress(email)
                                .orElseThrow(() -> new UsernameNotFoundException("User '" + email + "' not found."))
                );
    }
}

返回NullPointerException的测试类:

@SpringBootTest
public class UsersAndRolesTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void ww(){
        assertThat(userRepository, notNullValue());
    }

    @Test
    public void userExistsInDatabase(){
        assertThat(userRepository.findByEmailAddress("admin@mail.com").isPresent(), notNullValue());
    }

}

我尝试使用@ Repository,@ EnableJpaRepositories等注释,实际上是我找到的每个解决方案。 IntelliJ还用“无法自动装配。找不到'UserRepository'类型的bean。”突出显示userRepository

2 个答案:

答案 0 :(得分:2)

将此注释添加到您的UsersAndRolesTest类

  

@RunWith(SpringRunner.class)

答案 1 :(得分:2)

在vanillaSugar的回答指导下,我找到了解决方案。我缺少的是@RunWith(SpringRunner.class)注释,但这还不够。我已经意识到问题也与测试套件所在的软件包有关。我没有在问题中添加package行代码,这也是问题的一部分。

根据我发现的信息,@SpringBootApplication在应用程序的包层次结构中扫描其下的组件。仅添加@RunWith注释就导致了这个问题,但又有一个例外: java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

我还要做的是将测试类从先前的软件包-security.UsersAndRolesTest移至com.powderize.security.UsersAndRolesTest,这将“镜像”应用程序代码中的软件包。对于更高级的Spring开发人员来说可能很明显,但是花了我一段时间才发现它。

相关问题