autowired annotation in spring nullpointerexception code example
Example 1: NullpointerException while autowire
@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> {
List<My> findByName( String name );
}
Example 2: NullpointerException while autowire
@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" );
}
}
@Repository
public interface MyRepository extends CrudRepository<My, Long> {
List<My> findByName( String name );
}