zoukankan      html  css  js  c++  java
  • Spring之引用其他Bean

    1.新建实体类

    public class Person {
        
        private String name;
        private String age;
        private Car car;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
        public Car getCar() {
            return car;
        }
        public void setCar(Car car) {
            this.car = car;
        }
        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
        }
    }

    2.新建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"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
        
        <bean id="car" class="com.auguigu.spring.beans.Car">
            <constructor-arg value="Audi" type="java.lang.String"></constructor-arg>
            <constructor-arg value="Shanghai" type="java.lang.String"></constructor-arg>
            <constructor-arg value="30000" type="int"></constructor-arg>
        </bean>    
        <bean id="person" class="com.auguigu.spring.beans.Person">
            <property name="name" value="Tom"></property>
            <property name="age" value="23"></property>
            <property name="car" ref="car"></property>
        </bean>
    </beans>

    这里通过ref来引入car这个bean

    3.测试类Main

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("./applicationContext.xml");
            Person p = (Person) ctx.getBean("person");
            System.out.println(p);
        }
    }

    总结:

    可以使用property属性的ref建立bean之间的引用关系

  • 相关阅读:
    [转载] 十问 TiDB :关于架构设计的一些思考 TiDB
    blender low poly + unity 3d游戏制作
    d2js + activiti 备忘
    使用ActionFilterAttribute进行重定向注意事项
    一键发布部署vs插件[AntDeploy],让net开发者更幸福
    Docker常用命令
    C# 自然周,月,季度计算。
    .Net Core Web Api使用模型验证验证参数合法性
    WebApi 路由机制剖析
    WebApi路由机制详解
  • 原文地址:https://www.cnblogs.com/sdnu-zhang/p/8527359.html
Copyright © 2011-2022 走看看