Search code examples
javaspringspring-bootspring-mvcannotations

When to use dependency Injection in spring mvc?


I am working on a Spring MVC project where I am dealing with different types of services,Repositories i.e classes annotated with @Service and @Repository. I am confused with a couple of questions:

  • When to use @AutoWired annotation?

    I have seen various repositories using this:

      CourseRepository crepo=new CourseRepository();
    

    and I have seen this also

    @AutoWired
    private CourseRepository crepo;
    

    Which one of the above options should be used to get an instance of repository in Service class?

  • Can I use @AutoWired for classes which are not annotated with @Repository or @Service?

I am a beginner in this java world.Any help will be highly appreciated. Thanks


Solution

  • You use new for data objects, which in most modern architectures are passive (they're not "active records"). Everything else is a service object, and you should inject those. (The one place that you do use new is with an @Bean method, which is a "factory" that creates the service object; in this case you normally pass the dependencies as method parameters.)

    Note that it is recommended to use constructor injection instead of field injection; it makes your code easier to test, and it eliminates the possibility of certain kinds of errors. In fact, if using constructor injection, it's not required to have any Spring annotations in your service classes at all; beans can be registered using @Import instructions or @Bean methods on a configuration class.