spring(1)_控制反转_helloWorld_ioc

这是我学习spring第一个写的代码

使用spring的步骤

1.搭建环境拷贝jar包

2.新建一个applicationContext.xml文件(spring的配置文件)


spring的控制反转(ioc)的说明,ioc其实就是将对象的创建等过程交给spring容器来做,这就是控制反转


小demo


配置文件(这些约束可以从spring的文档自己抄)

<?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-2.5.xsd">

<!-- 
beans 存放了很多类
  把一个类放在spring容器中就是一个bean
  一个bean就是一个类
  
  id:是标示符,命名规范:类的第一个字符小写,其他一样
  class: 为类的全名
-->
<bean id="helloWorld" class="com.hxc.domain.HelloWorld">

</bean>

</beans>

HelloWorld类

package com.hxc.domain;


import java.io.Serializable;


public class HelloWorld implements Serializable{

public void helloWorld() {
System.out.println("你好,世界");
}
}

测试类

可以new一个ClassPathXmlApplicationContext,一定要在类路径下,就是项目的src目录下

package com.hxc.test;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.hxc.domain.HelloWorld;


public class TestHellloWorld {

@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld)applicationContext.getBean("helloWorld");
helloWorld.helloWorld();
}
}

结果

九月 04, 2016 10:45:09 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2b159eb: display name [org.springframework.context.support.ClassPathXmlApplicationContext@2b159eb]; startup date [Sun Sep 04 22:45:09 CST 2016]; root of context hierarchy
九月 04, 2016 10:45:09 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
九月 04, 2016 10:45:10 下午 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@2b159eb]: org.springframework.beans.factory.support.DefaultListableBeanFactory@38ff3be5
你好,世界
九月 04, 2016 10:45:10 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@38ff3be5: defining beans [helloWorld]; root of factory hierarchy




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值