如何使用idea的maven工程构建一个spring框架环境并实现一个简单的spring项目

**

如何使用idea的maven工程构建一个spring框架环境

**

第一次使用idea创建spring项目的小伙伴可能都会碰到各种问题,我也老是碰到问题,所以准备写个博客巩固下,方便以后使用,好了 闲话就不多说了 开始
首先得做个准备工作(电脑里得有idea和maven),项目所使用得包都是使用maven导入,所以没下载maven的还得下一个maven.

1.打开idea,新建项目(不是社区版,社区版没有JavaEE功能)

在这里插入图片描述在这里插入图片描述在这里插入图片描述一个使用maven的java项目就新建好了,接下来就要导入包了,使用了maven的话就很轻松了。
这是maven官网,需要什么包就可以去里面找

2.修改pom.xml文件
添加spring所需的依赖在这里插入图片描述spring依赖:

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

添加后import一下就可以了
在这里插入图片描述
3.我们可以查看项目结构,这是我们所需要的项目结构

在这里插入图片描述

准备阶段的工作就做完了,那就开始编写spring

4.首先在src包下的main包中的java包定义我们所需要的接口和实现类

在这里插入图片描述
接口代码如下

package com.yao.service;

public interface Service {
    public void doSome();
}

实现类代码如下

package com.yao.serviceImpl;

import com.yao.service.Service;

public class ServiceImpl implements Service {
    public void doSome() {
        System.out.println("执行dosome()方法");
    }
}

5.在resources包下创建一个配置文件applicationContext.xml
在这里插入图片描述配置文件代码如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="myservice" class="com.yao.serviceImpl.ServiceImpl"></bean>
    <!-- bean definitions here -->

</beans>

6.在test包下java包中定义一个测试类Mytest.java

测试类代码如下:

import com.yao.service.Service;
import com.yao.serviceImpl.ServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        Service myservice = (ServiceImpl) ac.getBean("myservice");
        myservice.doSome();
    }
}

7.最后执行程序,得到如下结果就说明spring框架已经搭建好啦

在这里插入图片描述

发布了4 篇原创文章 · 获赞 3 · 访问量 70

猜你喜欢

转载自blog.csdn.net/qq_45234751/article/details/105209844