Spring框架(一)

简介

Spring是一个基于IOC和AOP的结构J2EE系统的框架。IOC 反转控制 是Spring的基础,Inversion Of Control 简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象 DI 依赖注入 Dependency Inject. 简单地说就是拿到的对象的属性,已经被注入好相关值了,直接使用即可。

编写HelloSpring类,输出“Hello, Spring!”

  1. 添加Spring到项目中。Spring下载
  2. 编写配置文件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-4.3.xsd">
    	<!-- 通过bean元素声明需要Spring创建的实例。该实例的类型通过class属性指定,并通过id属性为该实例指定一个名称,以便在程序中使用 -->
    	<bean id="helloSpring" class="cn.springdemo.HelloSpring">
    		<!-- property元素用来为实例的属性赋值,此处实际是调用setWho()方法实现赋值操作 -->
    		<property name="who">
    			<!-- 此处将字符串"Spring"赋值给who属性 -->
    			<value>Spring</value>
    		</property>
    	</bean>
    </beans>
  3. 编写代码获取HelloSpring实例
    package cn.springdemo;
    
    /**
     * 第一个Spring,输出"Hello,Spring!"。
     * 
     * @author 日月之食焉
     */
    public class HelloSpring {
    	// 定义who属性,该属性的值将通过Spring框架进行设置
    	private String who = null;
    
    	/**
    	 * 定义打印方法,输出一句完整的问候。
    	 */
    	public void print() {
    		System.out.println("Hello," + this.getWho() + "!");
    	}
    
    	/**
    	 * 获得 who。
    	 * 
    	 * @return who
    	 */
    	public String getWho() {
    		return who;
    	}
    
    	/**
    	 * 设置 who。
    	 * 
    	 * @param who
    	 */
    	public void setWho(String who) {
    		this.who = who;
    	}
    
    }

     

  4. 编写测试代码
    package test;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.springdemo.HelloSpring;
    
    public class HelloSpringTest {
    
        @Test
        public void helloSpring() {
            // 通过ClassPathXmlApplicationContext实例化Spring的上下文
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            // 通过ApplicationContext的getBean()方法,根据id来获取bean的实例
            HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
            // 执行print()方法
            helloSpring.print();
        }
    }
    

     

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值