Trying to build a services named AccountService an I don't know why my @Autowired field is null. I tried multiple things like ComponentScan and all the stuff you find on google.
Thank you in advance :)
The class that is being auto wired:
package de.scroll.AccountService.Account;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface AccountRepository extends MongoRepository<Account, String> {
public Optional<Account> findById(String id);
public List<Account> findByEmailaddress(String email);
}
The class in which the the auto wired class should be in use:
package de.scroll.AccountService;
import de.scroll.AccountService.Account.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class AccountServiceApplication {
@Autowired
public static AccountRepository repository;
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
test();
}
public static void test() {
repository.findAll();
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at de.scroll.AccountService.AccountServiceApplication.test(AccountServiceApplication.java:22)
at de.scroll.AccountService.AccountServiceApplication.main(AccountServiceApplication.java:18)
CodePudding user response:
The field repository
is null
because you can't inject a bean with @Autowired
declared as a static field (see Can you use @Autowired with static fields? for more information).
CodePudding user response:
I have successfully used the @Autowired annotation in Spring Boot MVC app. But on the class I want to use, I use the @Component annotation.
@Component
public class RedshiftService {
....
}
Now I can @Autowired in a Controller class and it works fine:
@Controller
public class BlogController {
@Autowired
RedshiftService rs;
....
}