• 技术文章 >Java >java教程

    Spring4的详细介绍

    零下一度零下一度2017-07-20 19:09:27原创1176
    本篇文章的demo基于spring官网入门案例。当然,我做了一些改变。

    我的maven web项目结构如下:

    在pom.xml中添加spring的依赖:

    接下来我们开始创建需要用到的类:
    package com.mm.service;
    
    public interface MessageService {
    	String getMessage();
    }

     

    package com.mm.service.impl;
    
    import com.mm.service.MessageService;
    
    public class MessageServiceImpl implements MessageService{
    	@Override
    	public String getMessage() {
    		return "hello mm";
    	}
    }

    这里我不用spring配置文件形式的注入,于是,我新建了一个配置文件类

    package com.mm.main.spring;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import com.mm.service.MessageService;
    import com.mm.service.impl.MessageServiceImpl;
    
    @Configuration
    @ComponentScan(basePackages = "com.mm")
    public class ApplicationConfig {
        @Bean
        MessageService messageService() {
            return new MessageServiceImpl();
        }
    }

    新建一个bean来调用服务

    package com.mm.main.spring;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import com.mm.service.MessageService;
    
    @Component
    public class MessagePrinter {
    	@Autowired
    	private MessageService messageService;
    	public void printMessage() {
            System.out.println(this.messageService.getMessage());
        }
    }

    最后完成客户端的编写工作

    package com.mm.main.spring;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Client {
    	public static void main(String[] args) {
    		ApplicationContext context=new AnnotationConfigApplicationContext(ApplicationConfig.class);
    		MessagePrinter messagePrinter=context.getBean(MessagePrinter.class);
    		messagePrinter.printMessage();
    	}
    }

    后台打印如下:

    接下来我们用注解的方式注入,首先去掉配置文件类中的MessageService bean

    @Configuration
    @ComponentScan(basePackages = "com.mm")public class ApplicationConfig {//    @Bean//    MessageService messageService() {//        return new MessageServiceImpl();//    }}

    为MessageServiceImpl添加注解

    @Service//注解方式public class MessageServiceImpl implements MessageService{
        @Overridepublic String getMessage() {return "hello mm";
        }
    }

    同样完成输出

    以上就是Spring4的详细介绍的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Spring4 入门 快速
    上一篇:枚举的介绍及使用 下一篇:Tomcat 总体结构详解
    千万级数据并发解决方案

    相关文章推荐

    • 一起来理解Java中的泛型• java反射机制详细解析(总结分享)• 快速上手Java数据结构之字符串• java知识点详解之注解与元注解• 详细整理java枚举的使用总结
    1/1

    PHP中文网