Search code examples
javaspringjavabeans

Constructor works fine with and without @Autowired


I have tennisCoach object created by Spring framework:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml")   ;
Coach theCoach = context.getBean("tennisCoach", Coach.class);

Can't understand why I need @Autowired annotation in TennisCoach constructor in code below. It works fine with and without @Autowired annotation.

@Component
public class TennisCoach implements Coach {

    private FortuneService fortuneService;

    @Autowired
    public  TennisCoach(FortuneService theFortuneService) {
        fortuneService = theFortuneService;
    }

    @Override

    public String getDailyWorkout() {
        return "Practice your backhand volley";
    }

    @Override
    public String getDailyFortune() {
        return fortuneService.getFortune();
    }

}

UPD

Content of applicationContext.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.luv2code.springdemo"></context:component-scan>
    
    
</beans>

Solution

  • From @Autowired Javadoc:

    If a class only declares a single constructor to begin with, it will always be used, even if not annotated.
    

    Since Spring 4.3 you don’t need the @Autowired annotation as soon as you have the only constructor in your class.