1.springIOC初识

IOC,控制反转,从最浅显的角度来讲就是通过Spring容器来负责创建对象

大体的实现结构

1.首先有一个我们需要运行的类

2.在spring专属的xml配置文件中配置该类

3.启动容器 

4.从该容器中获取此类的对象

5.调用对象的方法

简单demo

1.导包,最基本的是spring.jar和commons-logging.jar

2.创建我们需要运行的类

public class HelloWorld {
	public void hello(){
		System.out.println("hello world");
	}
}

3.编写applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--beans里面的每个bean就是一个需要容器启动的类 -->
<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-2.5.xsd">
     <!--每个bean的id一般都命名为该类名的首字母小写的名字-->
	<bean id="helloWorld" class="HelloWorld的全类名"></bean>
    <!--每一个alias都是一个别名,name就是上面定义的id,alias就是别名-->
	<alias name="helloWorld" alias="王五"/>
	<alias name="helloWorld" alias="林志玲"/>
	<alias name="helloWorld" alias="赵六"/>
</beans>

4.启动容器,获取对象,调用方法

public class HelloWorldTest {
	@Test
	public void test(){
		/*
		 * 1、启动spring容器
		 * 2、从spring容器中把helloWorld拿出来
		 * 3、对象.方法
		 */
		//启动spring容器
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//配置文件的全路径
		HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");//根据配置文件中的id获取对象
		helloWorld.hello();
	}
}

  

转载于:https://www.cnblogs.com/Niel-3/p/7498543.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值