问题描述
谁能帮我? 我正在尝试使用Spring Data JPA配置Spring Security。 我使用Spring Boot,并想在CommandLineRunner.run()中填充数据库,所以我需要导入我的存储库,也需要UserDetailsS??ervice实现中的那些存储库。 在两个我都
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'
)
)
}
}
UserDetailsS??erviceImpl代码:
@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);
}
}
1楼
@Autowired,当您为相同的变量自动接线时,一旦确定,就对了。 例:
@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;
这样,一切都很好。