@Autowired says field injection not recommended

Viewed 12167

can anyone tell me why @autowired is saying field injection is not recommended and the TextWriter object 'text' also says it could not autowire because there is more than one bean of textwriter type. My code.

2 Answers

can anyone tell me why @autowired is saying field injection is not recommended ?

For a design reason. Injecting beans directly into fields makes your dependencies "hidden" and encourage bad design :

  • the class API (public/protected member) doesn't specify them while they exist.
  • no way to unit test without reflection or a Spring container (the most important part for me)
  • you may finish by declaring potentially many injected fields. Which may make your class with a strong coupling to other classes without that you are "really" aware of that.

Generally constructor injection should be favored (no need to annotate the constructor with @Autowired since Spring 4) if few fields, otherwise setters should be the way.
Both ways don't have all drawbacks mentioned above.

I assume Spring does not see your TextWriter class as a bean. Probably TextWriter is in another package. For example, in the “models” package. If you use Spring Boot, then this will help you:

@SpringBootApplication(scanBasePackages={"com.programwithwaqas.restservice.models"})

I recommend you read the @SpringBootApplication annotation. Pay attention to the annotation @ComponentScan.

This is in case you are not using Spring Boot

@ComponentScan(basePackages={"com.programwithwaqas.restservice.models"})
Related