public interface MyRepository extends CrudRepository<My, Long> {
List findByName( String name );
}
你好,2005呼叫并要求返回他们的代码。好吧,IoC就像是街上的帅小伙子一样,如果你使用的是Spring(自动注入),则需要一直使用它。这是Controller, Service 和 Repository的代码片段,它们将导致NullPointerException。
@Controller
public class Controller {
@GetMapping(“/example”)
public String example() {
MyService my = new MyService();
my.doStuff();
}
}
@Service
public class MyService() {
@Autowired
MyRepository repo;
public void doStuff() {
repo.findByName( “steve” );
}
}
当它尝试访问MyRepository自动连接的存储库时,这将在Service中引发NullPointerException,这不是因为Repository的连接有任何问题,而是因为你使用MyService my = new MyService()手动实例化了MyService。要解决此问题,需要自动注入MyService:
@Controller
public class Controller {
@Autowired
MyService service;
@GetMapping(“/example”)
public String example() {
service.doStuff();
}
}
@Service
public class MyService() {
@Autowired
MyRepository repo;
public void doStuff() {
repo.findByName( “steve” );
}
}
@Repository
public interface MyRepository extends CrudRepository<My, Long&