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

  • 相关阅读:
    SpringBoot jar包不支持jsp
    Spring Boot 启动报错:LoggingFailureAnalysisReporter
    spring boot与spring mvc的区别是什么?
    解决配置JAVA_HOME JDK版本不变的问题
    Linux下修改Mysql的用户(root)的密码
    CentOS/Linux 解决 SSH 连接慢
    Linux查看进程的所有子进程和线程
    Linux命令之pstree
    使用awk批量杀进程的命令
    lucene 自定义评分
  • 原文地址:https://www.cnblogs.com/lh218/p/6550647.html
Copyright © 2011-2022 走看看