spring配置讲解

Bean元素

引用块内容

Bean元素进阶

scope属性:

1.singleton(默认值):单例对象.被标识为单例的对象在spring容器中只会存在一个实例
2.prototype:多例原型.被标识为多例的对象,每次再获得才会创建.每次创建都是新的对象.整合struts2时,ActionBean必须配置为多例的.
3.request:web环境下.对象与request生命周期一致.
4, session:web环境下,对象与session生命周期一致.

生命周期属性

1.配置一个方法作为生命周期初始化方法.spring会在对象创建之后立即调用. init-method
2.配置一个方法作为生命周期的销毁方法.spring容器在关闭并销毁所有容器中的对象之前调用. destory-method(单例对象可以销毁,多例对象不会被销毁)
这里写图片描述

spring创建对象方式

1.空参构造方式
这里写图片描述
2.静态工厂(了解)
这里写图片描述这里写图片描述

spring的分模块配置

这里写图片描述

练习代码:
xml

    <bean name="user" class="com.spring.bean.User"  scope="singleton" init-method="init" destroy-method="destroy"></bean>

User类

package com.spring.bean;

public class User {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void init(){
        System.out.println("初始化");
    }
    public void destroy(){
        System.out.println("銷毀");
    }
}

Test类

package com.test;

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

import com.spring.bean.User;

public class TestDemo {
    private  ClassPathXmlApplicationContext context;
    @Test
    public void testDemo() throws InterruptedException{
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*scope=prototype的javaBean在创建容器时候不会被创建*/
        User bean = (User)context.getBean("user");
        //User bean1 = (User) context.getBean("user");
        //System.out.println(bean==bean1);
        bean.setName("DreamZuora");
        bean.setAge(18);
        System.out.println(bean);
        /*单例对象可以销毁,多例对象不会被销毁*/
        context.close();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值