JavaEE Spring 控制反转(依赖注入)

 Spring是一个当前Java EE轻量级框架,目的是使现有技术更加易用。Spring的诞生是为了满足企业级系统的一些需求,那么,Spring究竟带来了那些好处呢?

引入Spring之后,Spring的依赖注入可以统一管理和生成javabean,哪有需要调用就往哪注入,这种方式大大降低了开发难度,降低了代码的耦合度,给后期的维护也带来了方便。
同时spring的AOP还能将系统中那些类似于日志管理,事务等分布性比较强,但又必须有的代码集中生成,无需开发人员关注,提高工作效率。
控制反转(依赖注入)
当某个角色(比如一个java实例,调用者)需要另一个角色(另一个java实例,被调用者)的协助时,在传统的程序设计过程中,通常由调用者来创建被调用者的实例。但是在spring里,创建被调用者的工作不再由调用者来完成。因此被称为控制反转;创建被调用者实例的工作通常由spring容器来完成,然后注入调用者,因此也称为依赖注入。这样给程序带来很大的灵活性,这样也实现了我们的接口和实现的分离。
简而言之也就是说我们要获得一个对象,不由我们开发者自己创建,而是由我们的容器来注入给我们的程序来使用。
示例:使用Spring实现“控制反转”

在这里插入图片描述
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
	http://www.springframework.org/schema/beans/spring-beans-3.2.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>

类HelloSpring.java代码如下:

package cn.springdemo;
/**
 * 第一个Spring,输出"Hello,Spring!"。
 */
public class HelloSpring {
	// 定义who属性,该属性的值将通过Spring框架进行设置
	private String who = null;

	/**
	 * 定义打印方法,输出一句完整的问候。
	 */
	public void print() {
		System.out.println("Hello," + this.getWho() + "!");
	}

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

测试类HelloSpringTest.java代码如下:

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();
    }
}

输出结果:Hello,Spring!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值