spring学习之三: javabean和springbean赋值

最重要的是的是利用set方法赋值

首先创建spring项目,引来jar包

其次, xml配置   test创建测试包 创建vo包    创建student、school  并设置构造方法

public class School {
    
        private Student student;

        public Student getStudent() {
            return student;
        }

        public void setStudent(Student student) {
            this.student = student;
        }
        
    
}

package com.jd.vo;


public class Student {
    
    
}

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

    <bean id="stu" class="com.jd.vo.Student"></bean>
    
    <bean class="com.jd.vo.School">
        <property name="student" ref="stu"></property>
    </bean>
</beans>

再次设置test类:

public class test {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
        context.getBean(School.class).getStudent();
    }
}

BEAN生命周期

通过构造方法或工厂方法创建bean对象——>为bean属性赋值——>调用 bean 的初始化方法,即init-method指定方法——>bean实例化完毕,可以使用——>容器关闭, 调用 bean 的销毁方法,即destroy-method指定方法。

spring bean生命周期主要分为初始化创建、使用、销毁。

注意
在手动启动关闭容器使用AbstractApplicationContext代替ApplicationContext使用close()方法

init-method:在设置bean的属性后执行的自定义初始化方法,注意:①、该方法不能有参数;②、对象每创建一次就会执行一次该方法;

public class Student {

    private String

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值