010. Spring Bean引用关系

来源:互联网 发布:程序员翻墙干什么 编辑:程序博客网 时间:2024/06/06 02:10

1、创建Java项目:File -> New -> Java Project

2、引入必要jar包,项目结构如下
这里写图片描述

3、创建Authority实体类Authority.java

package com.spring.model;public class Authority {    private String authority = null;    public Authority() {        System.out.println("获取权限");    }    public String getAuthority() {        return authority;    }    public void setAuthority(String authority) {        this.authority = authority;    }    @Override    public String toString() {        return "Authority [authority=" + authority + "]";    }}

4、创建People实体类People.java

package com.spring.model;public class People {    private int id;    private String name;    private Authority authority = null;    public People() {        super();        System.out.println("Create People");    }    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 Authority getAuthority() {        return authority;    }    public void setAuthority(Authority authority) {        this.authority = authority;    }    @Override    public String toString() {        return "People [id=" + id + ", name=" + name + ", authority=" + authority + "]";    }}

5、创建spring配置文件applicationContext.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="people" class="com.spring.model.People" depends-on="authority">        <property name="id" value="0"></property>        <property name="name" value="管理员"></property>        <property name="authority" ref="authority"></property>    </bean>    <bean id="authority" class="com.spring.model.Authority">        <property name="authority" value="管理员权限"></property>    </bean></beans>

6、创建Spring测试类SpringUnit.java

package com.spring.junit;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.model.People;public class SpringUnit {    ClassPathXmlApplicationContext ctx = null;    @Before    public void setUp() throws Exception {        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");    }    @Test    public void test() {        People people = (People) ctx.getBean("people");        System.out.println(people.toString());    }    @After    public void tearDown() throws Exception {        ctx.close();    }}

7、测试结果

... 省略Spring日志信息 ...获取权限Create PeoplePeople [id=0, name=管理员, authority=Authority [authority=管理员权限]]... 省略Spring日志信息 ...
原创粉丝点击