码迷,mamicode.com
首页 > 编程语言 > 详细

spring使用FactoryBean给ioc容器加入组件

时间:2019-11-16 17:56:16      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:private   nbsp   package   object   创建   style   打印   throws   this   

FactoryBean是srping的一个接口,现在我们来创建一个类MyFactoryBean
来实现FactoryBean接口
package org.springframework.beans.factory;

public interface FactoryBean<T> {
    T getObject() throws Exception;

    Class<?> getObjectType();

    boolean isSingleton();
}
创建Person类
package com.springbean;

public class Person {

    private  String name;
    private Integer age ;

    public Person(String name) {
        this.name = name;
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

MyFactoryBean实现接口FactoryBean,重写三个方法

import org.springframework.beans.factory.FactoryBean;

public class MybeanFactory implements FactoryBean<Person> {

    @Override
    public Person getObject() throws Exception {
        return new Person("啦啦啦",22);
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

创建配置类MainConfig

@Configuration
public class MainConfig {

    @Bean
    public MybeanFactory mybeanFactory(){
        return new MybeanFactory();
    }

}

测试:

public class DemoTest {

    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);

    @Test
    public void test(){
        Object bean = applicationContext.getBean("mybeanFactory");
        System.out.println(bean.getClass());

    }
}

打印可以得到person类的全类名

 

打完收工。

 

 

spring使用FactoryBean给ioc容器加入组件

标签:private   nbsp   package   object   创建   style   打印   throws   this   

原文地址:https://www.cnblogs.com/tdyang/p/11872343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!