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

本文通过一个简单的示例介绍了如何使用Spring框架。通过Eclipse和Maven搭建开发环境,并创建了一个包含自动装配组件的小型应用程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值