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 trial

Java Adding Authentication

Binyamin Friedman
Binyamin Friedman
14,615 Points

What does @autowired do?

I know this has been explained, but I don't really understand. Why do we do this

@Autowired
UserRepository users;

instead of this?

UserRepository users = new UserRepository();

Also when do we use @Component?

2 Answers

Benyam Ephrem
Benyam Ephrem
16,505 Points

@Autowired is basically Spring injecting (doing the initializing of the variable) the variable in based on configurations you defined in classes with the @Component annotation. Further reference: @Autowired In Spring

@Component marks the class as a Java Bean and Spring picks that up and pulls it into the Application context so that it can be injected into @Autowired instances.

Basically, this is Spring making you do less work to initialize variables and a benefit is that you can change the component class without having to go back and change declarations of the variable, etc.

To add to what Benyam said. If you take a look at a couple of the other courses: Spring with Hibernate and Build a Rest API in Spark, you'll see some of the benefit of @Autowired.

In these courses they take an approach of building Model Classes and then Data Access Layer and a Data Service to make those available to something else. These layers are built per Model Class so if you imagine in a larger application with many Model classes how much extra work this would be. Using @Autowired with a Repository extending a CrudRepository takes care of this saving time and code.