1

I trying using Spring Data in my first Spring Boot application.

Person.java:

@Entity
@Table(name = "person")
public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    public Person() {
        super();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

PersonRepository.java:

public interface PersonRepository extends CrudRepository<Person, Long> {
}

PersonService.java:

public interface PersonService {
    void add(String name);
}

PersonServiceImpl:

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonRepository personRepository;

    @Transactional
    public void add(String name) {
        Person person = new Person();
        person.setName(name);
        personRepository.save(person);
    }
}

PersonConroller.java:

@SpringBootApplication
public class PersonController {
    @Autowired
    PersonService personService;

    public static void main(String args[]) {
        new PersonController().testAdd();
    }

    void testAdd() {
        personService.add("Nick");
    }

}

Error:

Exception in thread "main" java.lang.NullPointerException
    at com.art.controller.PersonController.testAdd(PersonController.java:17)
    at com.art.controller.PersonController.main(PersonController.java:13)

Why I have NullPointerException in testAdd()? Please explain

bsuart
  • 351
  • 1
  • 4
  • 24
  • Why do you think you shouldn't have a NullPointerException? – JB Nizet Jul 02 '17 at 19:37
  • @JBNizet I think that annotation Autowired doesn't work – bsuart Jul 02 '17 at 19:52
  • 1
    It works if you actually create a Spring context, and let Spring create the bean. If you never create any Spring context, and you create an object with new, Spring is out of the picture, and has no knowledge of the object you create, and thus can't possibly inject anything in that object. Read the Spring documentation. – JB Nizet Jul 02 '17 at 19:56
  • @JBNizet thanks, i understand – bsuart Jul 02 '17 at 19:57

0 Answers0