zoukankan      html  css  js  c++  java
  • bean的实例化方式

    spring中bean的实例化方式有三种,1.构造器实例化,2.实例工厂实例化,3.静态工厂实例化

    1.构造器实例化方式

    public class bean1 {
    public bean1() {
    }
    }
    applicatContext.xml中的配置
    <bean id="bean1" class="com.itheima.ioc.Constructorbean.bean1"/>
    测试
    public class consTest {
    public static void main(String[] args) {
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    bean1 bean=(bean1) applicationContext.getBean("bean1");
    }
    }

    2.静态工厂实例化bean
    public class Bean2 {
    public Bean2() {
    }
    }
    //静态工厂类
    public class MyFactoryBean2 {
    public static Bean2 creatBean() {
    return new Bean2();
    }
    }

    applicatContext.xml中的配置
    <bean id="bean2" class="com.itheima.ioc.StaticFactoryshilihuaBean2.MyFactoryBean2"
    factory-method="creatBean"/>
    测试:
    public class TestFactoryBean {
    public static void main(String[] args) {
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    Bean2 bean2=(Bean2)applicationContext.getBean("bean2");
    System.out.println(bean2);
    }
    }
    3.实例工厂实例化bean
    public class bean3 {
    }
    实例工厂类
    public class MyBeanFactory {
    public MyBeanFactory() {
    System.out.println("这是实例化工厂实例化bean...");
    }

    public bean3 createBeanFactory() {
    return new bean3();
    }
    }
    applicationContext.xml中的配置
     <bean id="MybeanFactory" class="com.itheima.ioc.shiligongcshilihBean3.MyBeanFactory"/>
    <bean id="bean3" factory-bean="MybeanFactory" factory-method="createBeanFactory"/>
    测试
    public class shilihuabeanTest {
    public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    bean3 bean=(bean3)applicationContext.getBean("bean3");
    System.out.println(bean);
    }
    }
  • 相关阅读:
    linux下修改Mysql的字符编码方式
    创建XMPP工程步骤
    ClickOnce清单签名取消后依然读取证书的问题
    FxCop卸载后依然生成文件夹的问题
    使用了旧版nuget的.net项目在git中的问题
    CorelDraw X8 破解激活问题
    ASUS T100TA 换屏要记
    百度SMS SDK for .Net
    网易闪电邮
    《The Practice and Theory of Bolshevism》的笔记-第114页
  • 原文地址:https://www.cnblogs.com/jasonboren/p/10565610.html
Copyright © 2011-2022 走看看