zoukankan      html  css  js  c++  java
  • 用静态工厂的方法实例化bean

    //代码如下:

    package com.timo.domain;
    
    public class ClientService {
        //use static factory method create bean
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public static ClientService getClientService() {
            return clientService;
        }
    
        public static void setClientService(ClientService clientService) {
            ClientService.clientService = clientService;
        }
    
        private static ClientService  clientService=new ClientService();
        private static People people=new People();
        private ClientService(){}
        public static ClientService createInstance(){
            clientService.setName("杨贵妃");
            return  clientService;
        }
        public static People createPeopleInstance(){
            return  people;
        }
    }

    配置文件

    applicationContext-static-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">
        <bean id="clientService" class="com.timo.domain.ClientService" factory-method="createInstance"/>
    </beans>

    测试类的代码如下:

    package com.timo.test;
    
    import com.timo.domain.ClientService;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test4 {
        public static void main(String[] args) {
            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-static-factory.xml");
            ClientService clientService = applicationContext.getBean(ClientService.class);
            System.out.println("name="+clientService.getName());
        }
    }
  • 相关阅读:
    YTU 2625: B 构造函数和析构函数
    YTU 2623: B 抽象类-形状
    YTU 2622: B 虚拟继承(虚基类)-沙发床(改错题)
    YTU 2621: B 继承 圆到圆柱体
    YTU 2620: B 链表操作
    YTU 2619: B 友元类-计算两点间距离
    刷题总结——切蛋糕(ssoj)
    刷题总结——拦截导弹(ssoj)
    算法复习——费用流模板(poj2135)
    算法复习——网络流模板(ssoj)
  • 原文地址:https://www.cnblogs.com/1540340840qls/p/7885114.html
Copyright © 2011-2022 走看看