简体   繁体   中英

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

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 want Spring to inject a field in Authenticator object the dependent object must be also created by Spring. You can do it by marking this class as a @Component or by creating a method with Authenticator return type marked with @Bean annotation. Then it must be injected somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM