Spring Framework 5.0:入手Spring、IoC容器、用户数据验证案列

本文介绍了Spring框架的基本概念,探讨了IoC容器的作用,并通过实例展示了如何使用Spring进行对象管理和配置。

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

spring是什么?

很多人听到spring,就里面想到做网站。实际上,做网站只是spring框架其中的一个小功能而已。

Spring Framework官网介绍:
https://projects.spring.io/spring-framework/#quick-start
注意:JDK 8+ for Spring Framework 5.x

使用maven下载:

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

文档地址:
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/
参考文献分为几个部分:Core、Testing、Data Access、Web Servlet、Web Reactive、Integration、Kotlin

Ioc容器 是什么?

今天我们要学习核心包Core里的IoC container

Inversion of Control (IoC):控制反转,本身是一种模式、设计思想,也并不是Spring特有的。

我们可以简单的理解:用容器来控制 对象的生命周期和相互直接的关系,而不是通过硬编码写在程序里。对象控制权交给独立第三方,而不是通过new Xoo()

要理解 IoC容器 的概念,必须结合案列

用户注册验证:1、用户名必须4位;2、QQ必填。
一段时候之后需求变了:1、用户名必须6位;2、QQ可以不填。
需求又变了:1、用户名必须8位;2、QQ必须填。

^^^^^^^^^多么蛋疼啊^^^^^^^^_^

对于这种情况,我们一般会创建:
1、一个验证配置类,比如叫做UserValidateConfig
2、一个操作类,比如叫做UserService

我们用代码演示一下
UserValidateConfig.java:

public class UserValidateConfig {
    private int UserNameLength; //用户名的长度
    private boolean QQRequired; //QQ是否必填

    public int getUserNameLength() {
        return UserNameLength;
    }

    public void setUserNameLength(int userNameLength) {
        UserNameLength = userNameLength;
    }

    public boolean isQQRequired() {
        return QQRequired;
    }

    public void setQQRequired(boolean QQRequired) {
        this.QQRequired = QQRequired;
    }
}

UserService.java:

public class UserService {

    UserValidateConfig userValidateConfig;

    public UserValidateConfig getUserValidateConfig() {
        return userValidateConfig;
    }

    public void setUserValidateConfig(UserValidateConfig userValidateConfig) {
        this.userValidateConfig = userValidateConfig;
    }

    public void userLogin(String user_name, String qq) throws Exception {
        if (user_name.length() < this.userValidateConfig.getUserNameLength()){
            throw  new Exception("用户名长度不合法");
        }
        if (this.userValidateConfig.isQQRequired() && qq.trim().equals("")){
            throw  new Exception("qq必填");
        }

        //
        System.out.println("用户开始登录...");
    }
}

最后在入口函数测试上2个类:

    public static void main(String[] args) throws Exception{
        UserService userService = new UserService();

        // 用户注册验证
        UserValidateConfig userValidateConfig = new UserValidateConfig();
        userValidateConfig.setUserNameLength(8);
        userValidateConfig.setQQRequired(true);

        // 用户登录操作 配置验证
        userService.setUserValidateConfig(userValidateConfig);

        // 准备登录
        userService.userLogin("zhangSan","111111111");
    }

这样当我们UserValidateConfig类发生变化,依赖它的UserService类也会发生变化。
前提提到的『用户注册』需求的变化,我们就可以只修改UserValidateConfig类。

Spring 框架中有什么高级用法

Spring中配置文件的创建参考文档:
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#beans-factory-xml-import

我们在项目resource目录下创建一个叫做userConfig.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">

    <!-- services -->

    <bean id="user_config" class="SpringLean.UserValidateConfig">
        <property name="UserNameLength" value="6"/>
        <property name="QQRequired" value="true"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

</beans>

看上面xml文档,好像我们是要把2个验证属性配置上了。

那么怎么使用到上面配置文件呢?

        // create and configure beans
        ApplicationContext context = new ClassPathXmlApplicationContext("userConfig.xml");

        UserValidateConfig userValidateConfig = (UserValidateConfig)context.getBean("user_config");

        System.out.println(userValidateConfig.getUserNameLength()); // 打印:6
        System.out.println(userValidateConfig.isQQRequired()); // 打印:true

打印的值和我们userConfig.xml这个配置文件里定义的一致呢。

比较2种 方式的差别

我们把需要对UserNameLengthQQRequired这2个属性的只,写到了userConfig.xml这个配置文件中。
这样就避免了像第一种方法那样new:

//        UserValidateConfig userValidateConfig = new UserValidateConfig();
//        userValidateConfig.setUserNameLength(8);
//        userValidateConfig.setQQRequired(true);

这个userConfig.xml就可以理解为Spring中的IoC容器

不仅如此,我们还可以配置UserServiceUserValidateConfig的依赖关系:

    <bean id="user_config" class="SpringLean.UserValidateConfig">
        <property name="UserNameLength" value="6"/>
        <property name="QQRequired" value="true"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>
    <bean id="user_service" class="SpringLean.UserService">
        <property name="userValidateConfig" ref="user_config"/>
    </bean>

从代码可以看出:id为user_service的依赖于id为user_config的。

用户登录验证代码就可以简化为如下:

        ApplicationContext context = new ClassPathXmlApplicationContext("userConfig.xml");

        // 从配置文件中设置好了相关验证
        UserService userService = (UserService)context.getBean("user_service");
        userService.userLogin("zhangSan","111111111");

如果没有感受到其中的魅力,不妨再来看看最初的方法:

        UserService userService = new UserService();

        // 用户注册验证
        UserValidateConfig userValidateConfig = new UserValidateConfig();
        userValidateConfig.setUserNameLength(8);
        userValidateConfig.setQQRequired(true);

        // 用户登录操作 配置验证
        userService.setUserValidateConfig(userValidateConfig);

        // 准备登录
        userService.userLogin("zhangSan","111111111");

很显然,需求再发现变化,我们都不需要改动代码,只修改配置文件即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值