我有一个JPA存储库的空指针异常,我认为存储库在@Autowired
时不需要实例化。
@Component
public class UserService {
@Autowired
UserRepository repository;
private Logger logger = LoggerFactory.getLogger(this.getClass());
public void createUser(User user) {
System.out.println("user email = " + user.getEmail());
repository.save(user);
}
...
应用
@ComponentScan({"mypackage", "mypackage.service"})
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
}
}
答案 0 :(得分:0)
@autowired用于根据applicationcontext.xml文件注入由spring容器预先实例化的bean,因此请确保在该文件中添加要注入的相应bean。 from spring's doc
答案 1 :(得分:0)
此UserService类必须使用注释(@Service / @AppService)而不是@Component。