Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Autowired not working in some classes

So i am using Spring to access my DB and fetch Users based on different Properties. With a @Restcontroller I get the Data. I created a UserRepository which extends the CrudRepository.

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Integer> {
Iterable<User> findByNachname(String nachname);

    Iterable<User> findByRolle(Rolle rolle);

    Optional<User> findByBenutzername(String benutzername);

    @Transactional
    String deleteByBenutzername(String benutzername);
}

I use @Autowire to get an Instance of the UserRepo in my Controller-class

@RestController
public class LoginController {
    @Autowired
    private UserRepository userRepository;
}

This works perfectly fine in all Controllers i have. But now when i try the same in another class the userRepository Instance is null.

public class Authentificator {
    @Autowired
    private UserRepository userRepository;
}

The Authentificator and the LoginController are not in the same package. But both of them are not in the same package as the UserRepo.

  • project
    • UserRepo-package
    • Controller-Package
    • Authentificator-Package
like image 921
Funny Crafter Avatar asked Mar 05 '23 00:03

Funny Crafter


2 Answers

you must make sure Authentificator is also a spring bean - I mean you must annotate it with something like @Component or @Service. After this step you’ll also have to “get” the Authentificator instance from spring instead of instantiating it with the new keyword.

like image 175
adrhc Avatar answered Mar 20 '23 09:03

adrhc


@Autowired does work only with the spring context. This means that it will work only with class instances which are managed by Spring. Your Authentificator class is managed by you and Spring does not have to take care or know about it, it's not important for the Java Framework.

This is more of a configuration issue rather than an annotation issue.

like image 34
Abhishek Anand Avatar answered Mar 20 '23 08:03

Abhishek Anand