Spring5.0的第一次尝鲜
2024-10-21 05:58: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; @Component
public 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
@ComponentScan
public 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!
}
}
最新文章
- web app响应式字体设置!rem之我见
- mysql在ubuntu下的安装
- 使用Diagnose服务查看Azure网站诊断信息
- September 1st 2016 Week 36th Thursday
- hibernate base
- 关于个人博客和Github地址提交
- android之TabHost(上)
- Bootstrap入门四:代码
- hadoop 序列化源码浅析
- IAR ARM、IAR STM8、IAR MSP430共用一个IDE
- 支付宝APP支付(Java后台生成签名具体步骤)
- Android Volley 之自己定义Request
- C语言关闭日志文件时忘了将日志文件全局变量指针置为NULL
- 你不可不知的Java引用类型之——SoftReference源码详解
- JAVA实现微信支付V3
- Java基础知识你知道多少?
- linux、内核源码、内核编译与配置、内核模块开发、内核启动流程(转)
- NBUT 1223 Friends number 2010辽宁省赛
- log4j配置详解(非常详细)
- How To Install Spring IDE In Eclipse
热门文章
- Ubuntu 14.04 或者16.04开启root账户登录和图形界面登录root时候的报错解决方法
- 改善程序与设计的55个具体做法 day7
- 让input表单输入框不记录输入过信息的方法
- [原创]Scala学习:关于变量(val,var,类型推断)
- poj 1419Graph Coloring 【dfs+补图+计算最大团+计算最大独立集 【模板】】
- 织梦dedecms 无法下载远程图片 fsockopen函数被禁用的解决方法
- C++拷贝构造函数(深拷贝,浅拷贝)
- jQuery学习(3)
- Sqlte 知识点记录
- 分享知识-快乐自己:PageHelper 分页关键基础代码