Spring基础用法

工具包:
1、spring-framework-4.0.4.RELEASE的21个RELEASE的jar包
2、commons-logging-1.2.jar
这里写图片描述
参数:
1、MyEclipse10
2、JDK1.7.0_79


1. 新建Java Project,新建类Person和Phone,导入工具包1和2

public class Person {
    private Phone phone;
    // set方法
    public void setPhone(Phone phone) {
        this.phone = phone;
    }
    public void usePhone() {
        phone.open();
    }
}
public class Phone {
    public void open() {
        System.out.println("开机");
    }
}

2. 配置管理Bean的方法

在src目录下新建配置文件beans.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.0.xsd">
    <!-- 配置id为person的Bean,实现类为com.zz.app.Person(调用无参构造方法) -->
    <bean id="person" class="com.zz.app.Person">
        <!-- 调用setPhone(Phone phone)方法,把id为phone1的Bean作为参数 -->
        <property name="phone" ref="phone1" />
    </bean>

    <!-- 配置id为phone1的Bean,实现类为com.zz.app.Phone -->
    <bean id="phone1" class="com.zz.app.Phone" />
</beans>

测试代码:

public class BeanTest {
    public static void main(String[] args) {
        // 创建Spring容器
        ApplicationContext ctx = new 
            ClassPathXmlApplicationContext("beans.xml");
        // 获得id为person的Bean
        Person p = ctx.getBean("person", Person.class);
        p.usePhone();
    }
}

编译、运行测试程序,可以看到以下输出:

十月 18, 2015 7:45:43 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@635a4247: startup date [Sun Oct 18 19:45:43 CST 2015]; root of context hierarchy
十月 18, 2015 7:45:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
开机


可以看出,根据beans.xml的配置,Spring已经装配了Person的phone属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值