Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSergei Makarov
13,839 Points@Autowired. Does it wire all Entities of CourseRepository?
Hello Craig,
could you please explain the point of @Autowired Annotation. Before I have thought, that it is just for all @Beans, that we have in our project, but now I can see, but we put this Annotation to constructor and you have said, that with it we "automatically wire up whatever we have labeled as the CourseRepository". Does that mean, that we wire up all the entities of CourseRepository, which will be for example saved (courses.save(course))?
And why we have to make it?
1 Answer
Boban Talevski
24,793 PointsI'm not entirely grasping how @Autowired works yet, but for anyone reading this question at a later date (since it's over a year old now), I would share my thoughts.
First of all, I don't think there's such a thing as all entities of CourseRepository, so can't understand what that part of the question is referring to.
Now, about the particular use of @Autowired in this case. We are telling the constructor of DatabaseLoader to get an object of type CourseRepository as a parameter. And how to get that object? Well, CourseRepository is an interface, so we can't create a new object of an interface like new CourseRepository() and Spring can't magically do that either. What Spring does behind the scenes is creating a class of that type for us, and than instantiate an object of that particular class which is passed as an argument to the constructor.
It's like Spring is writing the code for a class called CourseRepositoryImpl which implements CourseRepository and then implements all the requested methods. And it creates an object like
CourseRepository courseRepository = new CourseRepositoryImpl()
And then sends that courseRepository object as a parameter to the constructor when another part of that "Spring magic" instantiates an object of the DatabaseLoader class.