Spring入门(一)

    科技2022-07-14  132

    Spring是什么?

                    一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

    7个模块组成

    模块的介绍:后面会对各个模块进行介绍:持续更新~~~~~~~~~~

    Spring的特点

    方便解耦,简化开发:                Spring 就是一个大工厂,可以将所有对象的创建和依赖关系的维护交给 Spring 管理。方便集成各种优秀框架:             Spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如 Struts2、                                                                               Hibernate、MyBatis 等)的直接支持。降低 Java EE API 的使用难度:  Spring 对 Java EE 开发中非常难用的一些 API(JDBC、JavaMail、远程调用等)都提供                                                                  了封装,使这些 API 应用的难度大大降低。方便程序的测试:                         Spring 支持 JUnit4,可以通过注解方便地测试 Spring 程序。AOP 编程的支持:                        Spring 提供面向切面编程,可以方便地实现对程序进行权限拦截和运行监控等功能。声明式事务的支持:只需要通过配置就可以完成对事务的管理,而无须手动编程。

    第一个Spring程序

     

    开发流程:

    导入Spring相关Jar包编写实体类编写配置文件编写测试进行测试

    注 : spring 需要导入commons-logging进行日志记录 . 我们利用maven , 他会自动下载对应的依赖项 .

    1. 导入Jar包

    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency>

    为了代码编写方便,我这里多引入了 junit的模块:junit模块方便后面进行测试

    2. 编写实体类

    package com.hls.pojo; public class Hello { private String name; public void show(){ System.out.println(name); } }

    3. 编写配置文件

    <?xml version="1.0" encoding="UTF-8"?> <!--suppress ALL --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!-- 由 Spring容器创建该类的实例对象 --> <bean id="personDao" class="com.hls.pojo.Hello" > <property name="name" value="hello"></property> </bean> </beans>

     

    4. 进行测试

    import com.hls.pojo.Hello; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class test { @Test public void test1() { String resour="beans.xml"; ApplicationContext applicationContext=new ClassPathXmlApplicationContext(resour); Hello h=(Hello)applicationContext.getBean("personDao"); h.show(); } }

    运行测试,打印出hello就可以 了

    Processed: 0.018, SQL: 8