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 /> <bean /> <bean />

通过工厂创建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

相关文章:

  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-29
  • 2021-09-10
  • 2021-07-12
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-29
  • 2021-04-01
  • 2022-12-23
  • 2021-06-30
  • 2022-12-23
相关资源
相似解决方案