• 用实例工厂的方法实例化bean


    在实例化bean时,除了setter,constructor方法外,还有实例工厂方法,和静态工厂方法。

    看代码:

    People类的代码如下:

    package com.timo.domain;
    
    public class People {
        private String name;
        private Integer age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }

    //工厂方法如下:

    package com.timo.domain;
    
    public class PeopleFactory {
        private static People people=new People();
        //this is non-static method.
        public People createPeopleInstance(){
            return  people;
        }
    }

    配置文件

    applicationContext-instance-factory.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">
        <import resource="applicationContext.xml"/>
        <import resource="applicationContext2.xml"/>
        <bean id="peopleFactory" class="com.timo.domain.PeopleFactory"></bean>
        <bean id="people" factory-bean="peopleFactory" factory-method="createPeopleInstance">
            <property name="name" value="曹操"/>
            <property name="age" value="56"/>
          </bean>
    
        <!-- more bean definitions go here -->
    
    </beans>

    测试类如下:

    package com.timo.test;
    
    import com.timo.domain.People;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test5 {
        public static void main(String[] args) {
            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-instance-factory.xml");
            People people = applicationContext.getBean(People.class);
            System.out.println("name="+people.getName()+" age="+people.getAge());
        }
    }
  • 相关阅读:
    DataSnap(MIDAS)三层架构中,常用事件及其触发顺序
    如何让中间层MIDAS/DATASNAP支持大量的并发用户并且控制连接数量
    插件之注册插件和注册插件中的模块
    TField.ProviderFlags
    datasnap生命期LifeCycle
    datasnap服务器支持的参数类型
    TDSAuthenticationManager的用法
    泛型实现的对象池
    服务器端如何防止DDOS
    获得客户端的信息
  • 原文地址:https://www.cnblogs.com/1540340840qls/p/7885096.html
Copyright © 2020-2023  润新知