Spring 初探(一)(Spring起步实例)

来源:互联网 发布:淘宝店铺层级划分 编辑:程序博客网 时间:2024/06/06 07:29
spring基本功能初探概括Spring 开始部分:http://spring.io/guidesBuilding a RESTful Web Service这部分基本是完成url访问的数据返回问题,其基本的更能类似于Django这里基本描述了spring运行的基本过程,即通过Application.java中的启动部分的相应注释给出对package中某些部分的监听(响应情况)其中SpringBootApplication能够给出监听多种事件的规定(web controller\components等)打包命令 mvn clean compilemvn clean packageScheduling Tasks每隔5s打印出事件信息Consuming a RESTful Web Service这里实现的过程基本上是与Building a RESTful Web Service相对应的,这里的RestTemplate与后者的中RestController的注释相对应,前一个将json转化为java对象的格式,后者将java对象转化为json由于前者为对象解析,故解析时要给出对象键值格式。这里Application run函数用到了lambda表达式,在这里仅仅对于其赋值方式给予说明,lambda表达式如果要作为对象进行保存则必须赋以接口类型,常见的利用Thread作为调用的方法使用Runnable作为接口(调用run函数)故可以进行转型赋值。如:        Runnable obj0 = (Runnable)()->{System.out.println("Thired call");};        new Thread(obj0).start();        Object obj1 = (Runnable) ()->{System.out.println("fourth call.");};        new Thread((Runnable) obj1).start();所以也就能理解如下代码:    @Bean    public CommandLineRunner run(RestTemplate restTemplate)throws Exception{        return args -> {            Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);            log.info(quote.toString());        };}其中CommandLineRunner是一个接口,其调用的void run正是由lambda表达式定义的。spring官网完整的Application类的定义是@SpringBootApplicationpublic class Application {    private static final Logger log = LoggerFactory.getLogger(Application.class);    public static void main(String []args){                SpringApplication.run(Application.class);    }    @Bean    public RestTemplate restTemplate(RestTemplateBuilder builder){        return builder.build();    }    @Bean    public CommandLineRunner run(RestTemplate restTemplate)throws Exception{        return args -> {            Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);            log.info(quote.toString());        };    }}去掉使用的@Bean的实际实现逻辑为:@SpringBootApplicationpublic class Application implements CommandLineRunner {    private static final Logger log = LoggerFactory.getLogger(Application.class);    public static void main(String args[]) {        SpringApplication.run(Application.class);    }    @Override    public void run(String... strings) throws Exception {        RestTemplate restTemplate = new RestTemplate();        Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);        log.info(quote.toString());    }}明显的下面这个形式是易于理解的。通过观察源码可以发现SpringApplication.run是通过SpringApplication对Application.class进行初始化后调用run函数,故下面代码的implements的方式是可以理解的。对于第一种方法,由于builder.build为工厂函数返回相应的实例,一般使用@Bean的方式为return相应的实例再在依赖的类中进行调用,只不过那里返回的方式是通过将lambda匿名函数体返回给接口CommandLineRunner,由于仅有一个接口回调函数,故由java类型推断完成了反推。至于对接口中的run调用args及其函数体的过程是由CommandLineRunner决定的(相应的参看文档),a bean should run when it is contained within a SpringApplication也就是说SpringApplication与CommandLineRunner共同决定了对语句块的调用。
所以第一种代码没有利用bean的特性

0 0
原创粉丝点击