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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With