美文网首页
spring创建bean的三种方式

spring创建bean的三种方式

作者: 李霖神谷 | 来源:发表于2019-12-08 14:31 被阅读0次

    1.空参构造方法:
    空参构造方法是默认的,当在xml中配置bean的时候,当创建ioc容器的时候就会创建该bean。
    (1)首先需要导入spring的三个核心依赖,core,bean,context。

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>
    

    (2)xml配置文件对应的是domain中的实体类

     <bean id="people"  class="people"></bean>
    @Data
    public class people {
        private  String name;
        private int age;
        public  people(){
            System.out.println("我是空参构造方法");
        }
    

    测试:

    //        创建ioc容器
            ApplicationContext ap=new ClassPathXmlApplicationContext("application.xml");
            people p= ap.getBean("people",people.class);
    
    

    2.1有参构造方法:constructor-arg 标签存在name index ref,通过这些设置有参构造函数的执行类型·.

    import lombok.Data;
    
    @Data
    public class people {
        private  String name;
        private int age;
        public  people(){
            System.out.println("我是空参构造方法");
        }
        public  people(String name ,int age){
    
            System.out.println("我是有参构造方法one");
        }
        public  people(int age,String name ){
    
            System.out.println("我是有参构造方法tow");
        }
    }
     <bean id="people2"  class="people">
            <constructor-arg index="0" value="zhang">  </constructor-arg>
            <constructor-arg index="1" value="123">  </constructor-arg>
        </bean>
    

    2.实例工厂创建bean指的是通过工厂创建实例对象,首先需要创建工厂,在xml中也要配置工厂类。

    public class peopleFactory {
        public  people  newinstence(){
            return  new people();
        }
    }
     <bean id="factory" class="peopleFactory" ></bean>
        <bean id="people"  class="people" factory-bean="factory" factory-method="newinstence">
        </bean>
    

    静态工厂,只是将工厂中的方法设置为static的,不需要创建工厂的bean

    <bean id="people"   class="peopleFactory" factory-method="newinstence">
        </bean>
    public class peopleFactory {
        public  static people  newinstence(){
            return  new people();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:spring创建bean的三种方式

          本文链接:https://www.haomeiwen.com/subject/zvjmgctx.html