简介
本文介绍Spring注册Bean的方法:实现FactoryBean接口。
注册Bean的方法我写了一个系列,见:Spring注册Bean(提供Bean)-方法大全 – 自学精灵
方法概述
- 实现FactoryBean接口
- 将第1步的实现类注入容器
实例
FactoryBean接口的实现类
package com.knife.factoryBean; import com.knife.entity.MyBean; import org.springframework.beans.factory.FactoryBean; public class MyFactoryBean implements FactoryBean<MyBean> { @Override public MyBean getObject() throws Exception { // 这里可以进行一些其他操作,比如填充属性等 return new MyBean(); } @Override public Class<?> getObjectType() { return MyBean.class; } //是否单例(默认为true) //true:这个bean是单例,在容器中只保存一份 //false:多实例,每次获取都会创建一个新的bean; @Override public boolean isSingleton() { return true; } }
要注册的类(Bean)
package com.knife.entity; public class MyBean { public String sayHello() { return "Hello World"; } }
配置类(注册FactoryBean接口的实现类)
package com.knife.config; import com.knife.factoryBean.MyFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfiguration { @Bean public MyFactoryBean myFactoryBean() { return new MyFactoryBean(); } }
测试
package com.knife.controller; import com.knife.entity.MyBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired private MyBean myBean; @GetMapping("/test") public String test() { return myBean.sayHello(); } }
结果
请先
!