实现FactoryBean接口
package cn.tedu.demo;
public class MoonCake {
private String name="五仁月饼";
public void step1(){
System.out.println("和面");
}
public void step2(){
System.out.println("夹馅");
}
public void step3(){
System.out.println("造型");
}
}
package cn.tedu.demo;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@Component
public class MoonCakeFactory implements FactoryBean {
@Override
public Object getObject() throws Exception {
MoonCake moonCake=new MoonCake();
moonCake.step1();
moonCake.step2();
moonCake.step3();
return moonCake;
}
@Override
public Class<MoonCake> getObjectType() {
return MoonCake.class;
}
}
package cn.tedu.context;
import cn.tedu.demo.MoonCake;
import cn.tedu.demo.MoonCakeFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FactoryBeanConfig {
@Bean
/*spring会自动调用getObject() 自动创建MookCake对象 Spring存储的对象是MoonCake类型*/
public MoonCakeFactory moonCake(){
return new MoonCakeFactory();
}
}
@Test
public void moon(){
MoonCake moonCake=ctx.getBean(MoonCake.class);
System.out.println(moonCake);
}
和面
夹馅
造型
cn.tedu.demo.MoonCake@433defed
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_55740233/article/details/120803126
内容来源于网络,如有侵权,请联系作者删除!