Spring5.0的第一次尝鲜
来源:互联网 发布:js防水防水涂料 编辑:程序博客网 时间:2024/05/16 17:31
对于这次尝鲜,说白了和Spring5.0的新特性基本没有多大的关系,如果说您不小心进来了,却发发现文章的内容和标题似乎不太匹配,那么我将是非常的抱歉,因为这浪费了您宝贵的时间。但是我还是要说:因为这确实是Spring5.0中的一个demo.而我在这里写下这个Demo的原因是这个Demo全部是注解的配置,因为我的习惯还停留在XML的阶段。
好了,让我们引入context包吧,这里使用maven配置:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.0.RELEASE</version> </dependency></dependencies>
这个Demo的实现思路是这样的,首先我们定义一个接口,定义一个类,该类要调用该接口中的方法,但是又没有实现这个接口,此时我们可以考虑下怎么做呢?很简单的,在不涉及其他类的情况下貌似只能在该类中的该方法中使用匿名内部类的方式的完成,但是这和我们之前的说的是一致的,我们要解耦,就要注入。这个Demo说的就是注入。在该Demo中,这个类将该接口私有化并且最终化,以便是有构造器注入。然后在方法中直接调用即可。在配置类中使用匿名内部类的方式创建这个接口的bean。在main方法中首先加载配置类,获取上下文,然后用上下文调用方法所在的类,进而调用方法。其实真正的方法的执行体应该是接口的匿名实现类的方法。
package hello;public interface MessageService { String getMessage();}
package hello;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class MessagePrinter { /** * 定义私有的,最终的成员变量,并且使用构造器进行初始化 */ final private MessageService service; @Autowired public MessagePrinter(MessageService service) { this.service = service; } public void printMessage(){ System.out.println(service.getMessage()); }}
package hello;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScanpublic class Application { @Bean MessageService mockMessageService(){ return new MessageService() { public String getMessage() { return "Hello World!"; } }; } public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(Application.class); MessagePrinter printer = context.getBean(MessagePrinter.class); printer.printMessage();//Hello World! }}
阅读全文
1 0
- Spring5.0的第一次尝鲜
- spring5.0 之@Primary注解的应用
- Spring5.0 集成Fastjson
- 第一章:spring5.0概述
- spring5
- JavaScript2.0 :抢先尝鲜
- JavaScript2.0抢先尝鲜
- JavaScript2.0 :抢先尝鲜
- spring5.0 函数式web框架 webflux
- 初学 快速入门 Spring5.0框架
- spring5.0解决Log4jConfigListener过期问题
- Delphi 2005 失望的尝鲜!
- 尝鲜RHEV3.0 RHEV管理中心
- spring5.0 之依赖注入(Dependency Injection)
- Spring5.0完整源码、API文档下载地址
- Spring5 aop1
- C++0x尝鲜:用lambda表达式模拟Ruby的过程对象
- C++0x尝鲜:Variadic Function Templates(带变长参数的函数模板)
- 哈夫曼树+C怪谈
- Week6 513. Find Bottom Left Tree Value
- TaskAffinity
- 使用Jsp,Servlet等技术,该项目主要是实现用户登录,将数据库中的学生信息输出在浏览器上
- 文章标题
- Spring5.0的第一次尝鲜
- 协程和线程
- 假身份证
- proguard
- 了解NameNode
- 网贷平台数据分析爬取并存入mysql,生成csv
- hibernate之注解3
- Kotlin 协程的使用
- 软考嵌入式系统设计师2015年上午试题总结