0

first time using springboot and I've implemented an API that works successfully. However, I'm not 100% sure what @bean and @autowired do.

This is my main application class from which the app starts running. As you can see I have a bean at CommandLineRunner where I initialize my repository.

    public static void main(String[] args) {
        SpringApplication.run(app.class, args);
    }

    Faker faker = new Faker(); // Faker class which generates random names to populate repository
    Students temp = new Students(); 

    @Bean
    public CommandLineRunner setup(studentRepository repository) {
        return (args) -> {
            for(int i = 0; i<20; i++) //Populates repository with 20 different students 
            {
                String firstName = faker.name().firstName();
                String lastName = faker.name().lastName();
                repository.save(new Students(firstName, lastName, temp.generateEmail(firstName, lastName), temp.generateCourse(), faker.address().streetAddress(), faker.number().numberBetween(18,28)));
            }
            logger.info("The sample data has been generated");
        };
    }
}

Below is part of my controller class where all the mappings and requests are done. I have @autowired for the repository.

@RestController //Used to indicate that this is the controller class
public class controller {
    @Autowired 
    private studentRepository repository;

    //GET request which retrieves all the students in the repository. Returns 200 OK status if successfully retrieved 
    @RequestMapping(value="/Students", method = RequestMethod.GET)
    public ResponseEntity<List<Students>> getStudents()
    {
        List<Students> students =  (List<Students>) repository.findAll();
        if(students.isEmpty())
        {
            return new ResponseEntity(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity(students, HttpStatus.OK);
    }

I'm not sure if this is 100% right but does autowired here take the bean from the main app class where the repository is initialized and then takes its values from the main app class too and use it in the controller class?

mvantastic
  • 47
  • 3
  • 9
  • [Spring Autowire](http://www.baeldung.com/spring-autowire) and [Spring Bean](https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html). Happy reading. – Prav Oct 30 '17 at 22:21
  • Have you took a look at this post - [Difference between @Bean and @Autowired](https://stackoverflow.com/questions/34172888/difference-between-bean-and-autowired) on this website? – LHCHIN Oct 31 '17 at 01:40

0 Answers0