@Autowired does not work with my service

Asked

Viewed 690 times

1

I always run the method that accesses what is in another class with @Autowired it is null, follow the code below:

@Component
public class TokenAuthenticationService {

    @Autowired
    UserRoleServiceSecurity service;
    ...
    void addAuthentication(HttpServletResponse response, String username) throws IOException {
        UserRole us = service.buscarPorUsername(username); //Aqui fica nulo e solta um java.lang.NullPointerException: null
        System.out.println(us.getRole());

The Userroleservicesecurity.java class:

@Service
public class UserRoleServiceSecurity {

    @Autowired
    UsuarioRepository repository;

    @Autowired
    UsuarioRoleRepository usRepository;

    public UserRole buscarPorUsername(String username) {
        return usRepository.buscarUserUsername(username);
    }
} 
  • 2

    Is Userroleservicesecurity invalid? What error is displayed? How are you using Tokenauthenticationservice?

  • What are the packages? How is the ComponentScan?

  • I have not configured the Componentscan, I use this Userroleservicesecurity in other places and it works, It is the Userroleservicesecurity that comes null, all are in the same package.

  • What error appears? Usually when spring fails to initialize a bean it throws an error. The problem may also be in the repositories that the service depends on.

  • the error is: java.lang.Nullpointerexception: null at com.baima.security.TokenAuthenticationService.addAuthentication(Tokenauthenticationservice.java:36) ~[classes/:na] at com.baima.security.JWTLoginFilter.successfulAuthentication(Jwtloginfilter.java:47) ~[classes/:na] at org.springframework.security.web.Authentication.AbstractAuthenticationProcessingFilter.doFilter(Abstractauthenticationprocessingfilter.java:240) ~[spring-security-web-4.2.3.RELEASE. jar:4.2.3.RELEASE] at org.springframework ... Continue but exceed maximum size

  • How and in which class you are injecting TokenAuthenticationService?

Show 1 more comment

1 answer

0

I recommend watching @componantScan, put as attribute basePackage the path of your packages. Also, I recommend annotating your service class with the @Service annotation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.