Spring工厂模式

x33g5p2x  于2021-10-16 转载在 Spring  
字(1.2k)|赞(0)|评价(0)|浏览(146)

实现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

相关文章

微信公众号

最新文章

更多