zoukankan      html  css  js  c++  java
  • Spring基础(3) : 静态工厂和实例工厂创建bean

    public class Factory {
        public static Person staticCreate(){
            Person p = new Person();
            p.name="staticCreate";
            return p;
        }
    
        public Person instanceCreate(){
            Person p = new Person();
            p.name="instanceCreate";
            return p;
        }
    }
    
      public static void main(String[] args){
            ApplicationContext context = new ClassPathXmlApplicationContext("a.xml");
            Person p1 = context.getBean("p1",Person.class);
            Person p2 =context.getBean("p2",Person.class);
            System.out.println(p1.getName()+" "+p2.getName());
        }
    
    配置:
    <bean id="p1" class="com.Factory" factory-method="staticCreate"/> <bean id="fac" class="com.Factory"/> <bean id="p2" factory-bean="fac" factory-method="instanceCreate"/>

    通过工厂创建bean。

    运行打印:

    staticCreate instanceCreate

    =========================================================================================================================================

    注解方式:

    @Configuration
    public class Factory {
        @Bean("p1")
        public static Person staticCreate(){
            Person p = new Person();
            p.name="staticCreate";
            return p;
        }
        @Bean("p2")
        public Person instanceCreate(){
            Person p = new Person();
            p.name="instanceCreate";
            return p;
        }
    }
     public static void main(String[] args){
            ApplicationContext context = new AnnotationConfigApplicationContext(Factory.class);
            Person p1 = context.getBean("p1",Person.class);
            Person p2 = context.getBean("p2",Person.class);
            System.out.println(p1.getName());
            System.out.println(p2.getName());
        }

    输出:

    staticCreate
    instanceCreate

  • 相关阅读:
    1 绪论
    3.4 向量空间及其子空间的的基与维数
    3.3 极大线性无关组以及&向量的秩
    3.2 线性相关与线性无关的向量组
    3.1 n维向量空间及其子空间
    2.6 拉普拉斯定理
    2.5 克拉默法则
    2.4 行列式按行(列)展开
    2.3 行列式的性质
    2.2 n阶行列式的定义
  • 原文地址:https://www.cnblogs.com/lh218/p/6550647.html
Copyright © 2011-2022 走看看