zoukankan      html  css  js  c++  java
  • 用实例工厂的方法实例化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());
        }
    }
  • 相关阅读:
    用FOR XML PATH('') 实现一列多行拼接为一行
    RTC相关文章收集
    XML-RPC vs. RTC Format
    获取当前月份的第一天
    image读取流
    WAMP解决访问后显示"You don't have permission to access / on this server."
    cxGrid之checkbox小结
    CXGRID用法(取行、列值;定位选中某行等等)
    delphi显示Sqlite的Text字段
    使用TRoleAuth类对DataSnap服务端的接口授权
  • 原文地址:https://www.cnblogs.com/1540340840qls/p/7885096.html
Copyright © 2011-2022 走看看