#java #spring #spring-boot #jpa #spring-security
Вопрос:
Я выполняю аутентификацию с использованием имени пользователя и пароля, после чего получаю токен для отправки дальнейших запросов на изменение поля в базе данных. Регистрация прошла успешно. Аутентификация и получение токенов завершаются успешно. При выполнении запросов с токеном для определенного пользователя появляется ошибка NULL. Скажите мне, в чем может быть проблема ? почему он не находит его в базе данных? Возможно, есть более удобный способ внести изменения в базу данных, пожалуйста, скажите мне.
Ошибка и код:
request:
PUT http://localhost:8080/profile/updated/7
{ "description":"hello world"}
response:
{
"timestamp": "2021-07-16T22:36:57.169 00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/profile/updated/7"
}
СПОСОБ УПРАВЛЕНИЯ ПОКОЕМ:
@RestController
@RequestMapping(value="/profile")
public class UserActController {
UserServiceActProfile userServiceActProfile;
@Autowired
public UserActController(UserServiceActProfile userServiceActProfile){
this.userServiceActProfile=userServiceActProfile;
}
@RequestMapping(value = { "updated/{id}" },produces = "application/json", method = RequestMethod.PUT)
public ResponseEntity<?> updateDescription (@PathVariable Long id, @RequestBody User name ){
return userServiceActProfile.updateDescription(id,name);
}
Обслуживание:
@Service
public class UserServiceActProfile {
UserRepository userRepository;
public ResponseEntity<?> updateDescription(Long id, User ds){
User user = userRepository.findById(id).get();
user.setDescription(ds.getDescription());
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("Description update!"));
}
}
хранилище:
public interface UserRepository extends JpaRepository<User, Long>{
User findByUsername(String name);
User findByEmail(String name);
Optional<User> findById(Long Id);
}
CONFIG:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String LOGIN_ENDPOINT = "/auth/**";
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtUserService jwtUserService;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(LOGIN_ENDPOINT).permitAll()
.anyRequest().authenticated()
.and()
.apply(new JwtConfigurer(jwtTokenProvider))
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(jwtUserService)
.passwordEncoder(passwordEncoder);
}
}
ошибка:
ava.lang.NullPointerException: Cannot invoke "com.op.springboot.repository.UserRepository.findById(java.lang.Long)" because "this.userRepository" is null] with root cause
java.lang.NullPointerException: Cannot invoke "com.op.springboot.repository.UserRepository.findById(java.lang.Long)" because "this.userRepository" is null
at com.op.springboot.service.UserServiceActProfile.updateDescription(UserServiceActProfile.java:16) ~[classes/:na]
at com.op.springboot.controller.UserActController.updateDescription(UserActController.java:34) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.8.jar:5.3.8]
Ответ №1:
Новое сообщение об ошибке NPE сообщает вам, что именно равно нулю и где. Вы нигде не инициализировали userRepository
; для этого вам нужен конструктор, как и в вашем контроллере ( @Autowired
не требуется, если у вас есть только один конструктор для класса).
В общем, создание полей зависимостей , подобных userRepository
final
, является хорошей практикой; если вы добавите final
, компилятор сообщит вам, что вы нигде его не инициализируете.