认识Spring初体验

认识Spring

1.Spring 是一个从实际开发中抽取出来的框架,企业级应用开发的 一站式 选择,贯穿表现层、业务层和持久层。具有高开放性,并能与其他框架无缝整合,俗称 架构粘合剂
2.Spring 有两大核心功能:控制反转 / 依赖注入 IOC/DI 面向切面编程 AOP
3.对于开发者来说,开发者使用 Spring 框架主要是做两件事:①开发 Bean ;②配置 Bean
4.Spring 容器作为超级大工厂,负责创建、管理所有的 Java 对象,这些 Java 对象被称为 Bean

使用maven搭建Spring

步骤一 编写HelloSpring

package com.niit.springtest;

public class HelloSpring {

    public String who="";

    public void hello(){
        System.out.println("Hello"+this.who);
    }

    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }
}

步骤二 添加Spring依赖

<!--Spring 的依赖支持--> 
<dependency>
<groupId>org.springframework</groupId> 
<artifactId>spring-context</artifactId> 
<version>3.2.18.RELEASE</version> 
</dependency> 
<dependency> 
<groupId>org.springframework</groupId> 
<artifactId>spring-core</artifactId> 
<version>3.2.18.RELEASE</version> 
</dependency> 
<dependency> 
<groupId>org.springframework</groupId> 
<artifactId>spring-beans</artifactId> 
<version>3.2.18.RELEASE</version> 
</dependency> 
<dependency> 
<groupId>org.springframework</groupId> 
<artifactId>spring-expression</artifactId> 
<version>3.2.18.RELEASE</version> 
</dependency>

步骤三 编写spring的配置文件 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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--创建HelloSpring类的对象-->
    <bean id="helloSpring" class="com.niit.springtest.HelloSpring">
        <!--给属性who赋值-->
        <property name="who" value="SpringTwo"/>
    </bean>

</beans>

步骤四 编写测试类调用Spring创建的bean (需要在pom.xml引入junit)

package test;

import com.niit.springtest.HelloSpring;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    @Test
    public void testOne(){
        //传统方法
        HelloSpring helloCommon = new HelloSpring();
        helloCommon.who="spring";
        helloCommon.hello();

        //使用Spring如何调用,创建对象的 不再由java类来处理
        // 而是提交给Spring容器来处理
        //初始化Spring的上下文
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //通过上下文对象的getbean()方法来,获取指定Id的实例
        HelloSpring helloSpring=(HelloSpring)context.getBean("helloSpring");
        helloSpring.hello();

    }
}

运行结果

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值