Java框架Spring入门-第一个spring项目

吃猫的鱼
2023-03-08 / 0 评论 / 269 阅读 / 正在检测是否收录...

spring 框架通过maven方式引入

    <dependencies>
        <!--
         这个jar 文件包含Spring 框架基本的核心工具类。Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心,当然你也可以在自己的应用系统中使用这些工具类。
外部依赖Commons Logging, (Log4J)。
         -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!--
        这个jar 文件是所有应用都要用到的,它包含访问配置文件、创建和管理bean 以及进行Inversion ofControl / Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件就可以了。
外部依赖spring-core,(CGLIB)。
        -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!--
这个jar 文件为Spring 核心提供了大量扩展。可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI 所需的全部类,instrumentation组件以及校验Validation 方面的相关类。
外部依赖spring-beans, (spring-aop)。
        -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
    </dependencies>

第一个spring 项目

首先新建一个类UserEntity:

public class UserEntity {
    public void addUser(){
        System.out.println("添加用户");
    }
}

在resourse目录下,新建一个spring.xml文件。

注入一个bean对象,id命名格式为类名首字母小写,class是类的完整路径地址,bean 的id不允许重复

spring.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">
<!--配置注入spring bean对象  bean 的id不允许重复
    bean的id命名格式一般为类名首字母小写
    class 是类的完整路径地址
-->
    <bean id="userEntity" class="cn.fish9.spring.UserEntity">
    </bean>
</beans>

在test目录下调用bean对象

public class Test01 {
    public static void main(String[] args) {
        //new UserEntity()
        // 1.读取xml配置文件
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
        // 2.根据bean的id获取bean对象
        UserEntity userEntity = classPathXmlApplicationContext.getBean("userEntity", UserEntity.class);
        System.out.println(userEntity);
        userEntity.addUser();
    }
}

1

评论 (0)

取消
友情链接 文章阅读: 网站地图