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!    }}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 扣分超过36分怎么办 护士资格证过期了怎么办 辞职护士执业证怎么办 网约护士怎么办手续 动车票待核验怎么办 店员不维护老板怎么办 准考证号会过期怎么办 驾校准考证丢了怎么办 科目二下大雨怎么办 考科目二下雨天怎么办 普通话总是二乙怎么办 科目二很紧张怎么办 18年科目四缺考怎么办 个人医保卡欠费怎么办 医保欠费不想交怎么办 怀化市驾考绿色通道怎么办? 签注易不能办理怎么办 网上怎么办护照和签证 意大利被偷护照怎么办 户口在学校 怎么办签证 户口换了身份证怎么办 广州在校大学生怎么办护照 民间借贷无法还怎么办 退伍档案没接收怎么办 档案被单位扣住怎么办 公积金提不出来怎么办 公积金还贷款怎么办手续 科一预约失败怎么办 科四忘记预约怎么办 我科目一缺考了怎么办? 无可选考试场地怎么办 早产儿脑部发育不好怎么办 宝宝脑部发育不好怎么办 小孩脑部发育不好怎么办 8岁儿童智力低下怎么办 儿童食物不耐受怎么办 忘记就诊卡号怎么办 nt检查预约不到怎么办 听力不好科目三怎么办 青岛公安不立案怎么办 长春驾照丢了怎么办