Spring ioc 例子

来源:互联网 发布:dw做淘宝导航条 编辑:程序博客网 时间:2024/05/18 03:04
<?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.sanmao.spring.ioc.HelloWorld"></bean>        <!--alias  别名-->    <alias name="helloWorld" alias="三毛"></alias></beans>
package com.sanmao.spring.ioc;/** * Created by root on 16-9-25. */public class HelloWorld {    public void sayHello(){        System.out.println("spring 在默认的情况下,使用默认的构造函数");    }}
package com.sanmao.spring.test;import com.sanmao.spring.ioc.HelloWorld;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * spring容器做的事情: *    解析spring的配置文件,利用Java的反射机制创建对象 * */public class testHelloWorld {    @Test    public void testHelloWorld(){        //启动sping容器        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        //从spring容器中把对象提取出来        HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorld");        helloWorld.sayHello();        HelloWorld alias=(HelloWorld)context.getBean("三毛");        alias.sayHello();    }}
0 0