spring使用FactoryBean给ioc容器加入组件
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring使用FactoryBean给ioc容器加入组件相关的知识,希望对你有一定的参考价值。
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容器加入组件的主要内容,如果未能解决你的问题,请参考以下文章