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-Windows文件上传Linux
    linux-ifconfig 查看没有IP
    springBoot 发布war/jar包到tomcat(idea)
    linux-常用命令
    (转)JVM各种内存溢出是否产生dump
    数据库缓存的几种方式
    使用jprofiler分析dump文件一个实例
    Hibernate之一级缓存和二级缓存
    最佳实践 缓存穿透,瞬间并发,缓存雪崩的解决方法
    缓存与数据库一致性之三:缓存穿透、缓存雪崩、key重建方案
  • 原文地址:https://www.cnblogs.com/jasonboren/p/10565610.html
Copyright © 2011-2022 走看看