1. 程式人生 > >Eclipse 配置第一個Spring Framework專案 with Maven

Eclipse 配置第一個Spring Framework專案 with Maven

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!”

這裡寫圖片描述