私は、スプリングブート、スプリングセキュリティとスプリングデータを使用するWebアプリケーションを持っています。ステートレスです。SpringCacheBasedUserCache is null
私は、ユーザーアセスのためのDBを呼び出すなかれするために避けたいと思います。だから私はSpringCacheBasedUserCacheを使用して考えています。
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("city"), new ConcurrentMapCache("userCache")));
return cacheManager;
}
@Bean
public UserCache userCache() throws Exception {
Cache cache = (Cache) cacheManager().getCache("userCache");
return new SpringCacheBasedUserCache(cache);
}
}
@EnableCaching
@Configuration
@EnableWebSecurity
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return new UserServiceImpl(commerceReposiotry, repository, defaultConfigRepository);
}
...
}
私はloadUserByUsername方法でUserDetailsService
@Service
public class UserServiceImpl implements UserDetailsService, UserService {
private final CommerceRepository commerceReposiotry;
private final UserAppRepository repository;
private final DefaultConfigRepository defaultConfigRepository;
@Autowired
private UserCache userCache;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
public UserServiceImpl(final CommerceRepository commerceReposiotry, final UserAppRepository repository, final DefaultConfigRepository defaultConfigRepository) {
this.commerceReposiotry = commerceReposiotry;
this.repository = repository;
this.defaultConfigRepository = defaultConfigRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails user = userCache.getUserFromCache(username);
UserApp userapp = null;
if (user == null) {
userapp = repository.findByUsername(username);
}
if (userapp == null) {
throw new UsernameNotFoundException("Username " + username + " not found");
}
userCache.putUserInCache(user);
return new CustomUserDetails(userapp);
}
...
}
を実装UserDetailsを実装し、別のクラスを持って、userCacheは(提案として)のいずれかがuserDetailsServiceBean
法または上@Bean
を置く
あなたの 'UserServiceImpl'はスプリングマネージドBeanではないので、何も注入されません。次に、コードに欠陥があります。あなたがキャッシュに入れた 'user'は常に' null'です。 –
自分でキャッシュするのではなく、自分の重大な作業を行う 'CachingUserDetailsService'に自分の' UserDetailsService'をラップするだけです。 –