Spring探究-----从HelloWorld开始

   1. Spring简介

1.1 什么是Spring

     Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其

著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解

决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用

哪一个组件,同时为 J2EE 应用程序开发提供集成的框架。Spring使用基本的JavaBean来完成以前只可能

由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而

言,任何Java应用都可以从Spring中受益。Spring的核心是控制反转(IoC)和面向切面(AOP)。简单来

说,Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架

1.2 Spring的优点

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

   2. Spring的第一个HelloWorld

实体类

package com.spring.helloworld;

/**
 * Spring的第一个HelloWorld
 * 
 * @author yyx 2019年9月24日
 */
public class HelloWorld {
    private String info;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public void sayHelloWorld() {
        System.out.println(info);
    }
}

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="helloWorld" class="com.spring.helloworld.HelloWorld">
        <property name="info" value="Spring的第一个HelloWorld"></property>
    </bean>
</beans>

测试类

package com.spring.helloworld;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * 测试
 * @author yyx 2019年9月25日
 */
public class HelloWorldTest {
    public static void main(String[] args) {
        ApplicationContext aContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        // helloWorld对应的配置文件中bean的ID
        HelloWorld helloWorld = (HelloWorld) aContext.getBean("helloWorld");
        helloWorld.sayHelloWorld();
    }
}

猜你喜欢

转载自www.cnblogs.com/fengfuwanliu/p/11565601.html