Eclipse 配置第一个Spring Framework项目 with Maven

https://blog.csdn.net/Joseph_Cherry/article/details/76863213

Spring框架是企业后端开发常用框架,作为一个Java工程师,这个框架几乎是必会的,下面就来一篇小白向的文章,用官网上的例子spring框架官网带大家来开发第一个Spirng Framework程序。

IDE:Eclipse Oxygen 
Build Tool:Maven

首先安装好这Eclipse Java EE,不是最新的也行,然后配置好Maven,这个网上可以搜到教程,本文重点不在这,所以不赘述。

新建一个Maven工程,选择quick start, 
这里写图片描述

然后填写好项目的基本信息,点击 Finish, 
这里写图片描述

下面是这个工程的目录: 
这里写图片描述

首先,在pom.xml中加入Spring框架的依赖关系,让maven导入spring相关的包,注意dependencies和dependency的区别

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.10.RELEASE</version>
    </dependency>
</dependencies>

 

在我的项目中,maven事先导入了Junit的包,所以截图是这样的: 
这里写图片描述

ctrl + s,maven就会帮你导入包了。

下面在src目录下新建一个接口MessageService,其中提供了一个getMessage方法

package com.hualuo.FirstSpringFramework;

public interface MessageService {
    String getMessage();
}

 

新建MessagePrinter类,作为消息的打印者,里面组合了一个MessageService成员。

package com.hualuo.FirstSpringFramework;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessagePrinter {
    private final MessageService service;

    @Autowired
    public MessagePrinter(MessageService service) {
        this.service = service;
    }

    public void printMessage() {
        System.out.println(this.service.getMessage());
    }
}
 

在 App类中填入代码:

package com.hualuo.FirstSpringFramework;

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;

/**
 * Hello world!
 *
 */
@Configuration
@ComponentScan
public class App {

    @Bean
    MessageService mockMessageService() {
        return new MessageService() {

            public String getMessage() {
                // TODO Auto-generated method stub
                return "Hello world!";
            }
        };
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        MessagePrinter printer = context.getBean(MessagePrinter.class);
        printer.printMessage();
    }
}

 

简单分析: 
@Autowired表示自动装配,@Bean表示标志为Bean,当context调用getBean的时候,就将注解为@Bean的mockMessageService方法返回的MessageService注入到MessagePrinter的setter方法中,从而实现自动注入,从而getBean返回了MessagePrinter对象,最终输出”Hello world!”

这里写图片描述

posted @ 2018-08-30 09:07  麦兜爱学习  阅读(1160)  评论(0编辑  收藏  举报