码迷,mamicode.com
首页 > 编程语言 > 详细

spring的bean管理

时间:2015-03-04 18:42:15      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

1、所有的类都可以交给Spring管理

2、如何把一个类交给bean管理?

(1)配置applicationContext.xml

(2)在xml中写入bean节点配置要交给bean管理的类

3、程序测试

(1)导入spring core container的jar包,spring核心包含以下包:

技术分享

(2)新建applicationContext.xml文件,这个文件要放在src文件夹下边,要不然找不到文件,配置根节点beans,并指定命名空间:

技术分享

<?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></bean>

</beans>

(3)配置bean节点,假设有一个User实体类

public class User {
    int id;
    String name;
    String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
}

(4)配置到bean管理的格式可以使用id指定一个对象名,

  也可以使用name指定多个别名,

      同时,class指定bean关联的类的完全限定名,

  如果要初始化可以指定init-method,

      如果销毁时需要做工作,指定destory-method

  默认是单例模式,如果非单例模式,需要在scope中指定scope="prototype"

  如果要指定懒加载,指定lazy-init

<bean id="user1" class="com.spring1.entity.User" init-method="init" destroy-method="destory"/>

在junit中测试:

@Test
    public void test() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user1 = (User) ac.getBean("user1");
    }

可看到获取对象成功。

 

spring的bean管理

标签:

原文地址:http://www.cnblogs.com/hpustudent/p/4314019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!