ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring 框架搭建

2021-09-12 18:33:28  阅读:167  来源: 互联网

标签:xml 框架 Spring xxx test UserService main com 搭建


1 Spring 框架搭建

第一步:新建 Maven 项目、设置项目坐标以及Maven环境:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

设置项目的名称和存放的工作空间:

在这里插入图片描述


第二步:

调整JDK版本

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
</properties>

修改单元测试 JUnit 版本

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.12</version>
 <scope>test</scope>
</dependency>

删除build标签中的pluginManagement标签

<!--删除build标签中的pluginManagement标签-->
<build>
</build>

在Maven仓库:https://mvnrepository.com/中搜索Maven仓库:https://mvnrepository.com/

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

第三步: 在main的java目录下新建包名 com.xxx.service,并新建UserService类:

package com.xxx.service;

public class UserService {
    public void test() {
        System.out.println("用户服务测试");
    }

}

在java同级目录下添加resouces目录,将 resources 标记为资源目录,在 src\main\resources 目录下新建 spring.xml 文件,并拷贝官网文档提供的模板内容到 xml
中。配置 bean 到 xml 中,把对应 bean 纳入到 Spring 容器来管理

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="userService" class="com.xxx.service.UserService">
        <!-- collaborators and configuration for this bean go here -->
    </bean>
    <!-- more bean definitions go here -->
</beans>

第四步,测试:在main的java目录下新建包名 com.xxx.test,并新建Start01类:

package com.xxx.test;

import com.xxx.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Start01 {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.test();

    }
}

  • 通过ClassPathXmlApplicationContext即可得到spring的上下文环境。
  • 通过getBean的id则可以返回一个对象,再进行类型强制转换则可以得到实例化好的UserService对象,不需要进行new的操作,new的操作则分配给了IOC进行工作。

标签:xml,框架,Spring,xxx,test,UserService,main,com,搭建
来源: https://blog.csdn.net/baidu_41922918/article/details/120253883

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有