Spring引导中的Bean和autowired注释

时间:2017-10-30 22:01:55

标签: spring api

第一次使用springboot并且我已经实现了一个成功运行的API。但是,我并不完全确定@bean和@autowired的作用。

这是应用程序开始运行的主应用程序类。 正如您所看到的,我在CommandLineRunner中有一个bean,我初始化了我的存储库。

    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");
        };
    }
}

以下是我的控制器类的一部分,其中完成了所有映射和请求。我为存储库安装了@autowired。

@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);
    }

我不确定这是100%正确但是在这里自动装配从初始化存储库的主应用程序类获取bean,然后从主应用程序类获取其值并在控制器中使用它类?

0 个答案:

没有答案
相关问题