任何人都可以帮助我吗?我试图用Spring Data JPA配置Spring Security。我使用Spring Boot并希望在CommandLineRunner.run()中填充数据库,因此我需要导入我的存储库,我也需要在UserDetailsService实现中使用这些存储库。在这两个我得到
Caused by: java.lang.IllegalArgumentException: Repository interface must not be null on initialization!
申请代码:
@SpringBootApplication
@EnableJpaRepositories
@PropertySource('classpath:application.properties')
class DemoApplication implements CommandLineRunner {
@Autowired
Environment environment
@Autowired
UserRepository userRepository
@Autowired
UserRoleRepository userRoleRepository
static void main(String[] args) {
SpringApplication.run DemoApplication, args
}
@Bean
DataSource dataSource() {
def source = new DriverManagerDataSource(
environment.getProperty("jdbc.host"),
environment.getProperty("jdbc.login"),
environment.getProperty("jdbc.password")
)
source.setDriverClassName(environment.getProperty("jdbc.driver"))
return source
}
@Override
public void run(String... args) throws Exception {
def user = new User(
username: 'user',
password: 'user'
)
def admin = new User(
username: 'admin',
password: 'admin'
)
userRoleRepository.deleteAll()
userRepository.deleteAll()
userRepository.save(user)
userRepository.save(admin)
userRoleRepository.save(
new UserRole(
user: user,
role: 'ROLE_USER'
)
)
userRoleRepository.save(
new UserRole(
user: admin,
role: 'ROLE_USER'
)
)
userRoleRepository.save(
new UserRole(
user: admin,
role: 'ROLE_ADMIN'
)
)
}
}
UserDetailsServiceImpl代码:
@Service('userDetailsService')
class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository
@Override
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
def user = userRepository.findOne(username)
return new org.springframework.security.core.userdetails.User(
user.username,
user.password,
buildUserAuthority(user.userRole)
)
}
Collection<? extends GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
return new ArrayList<GrantedAuthority>(setAuths);
}
}
答案 0 :(得分:0)
@ Autowired,当你自动装配相同的var时,一旦没问题,你是对的。 例如:
@Service("notifyRegService")
public class NotifyRegServiceImpl implements INotifyRegService {
@Autowired
private NotifyConfigProperties notifyConfigProperties;
@Autowired
NotifyRepository notifyRepository;
@Service("notifyOffService")
public class NotifyOffServiceImpl implements INotifyOffService {
@Autowired
private NotifyConfigProperties notifyConfigProperties;
// @Autowired
NotifyRepository notifyRepository;
像这样,一切都很好。