Bean的实例化

Bean的实例化

  • 构造器实例化(最常用)

  • 静态工厂方式实例化

  • 实例工厂方式实例化

构造器实例化(最常用)

public class Bean1 {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="bean1" class="com.itheima.instance.constructor.Bean1"></bean>
</beans>
public class InstanceTest1 {
   public static void main(String[] args) {
       String xmlPath = "com/itheima/instance/constructor/bean1.xml";
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
       Bean1 bean = (Bean1) applicationContext.getBean("bean1");
       System.out.println(bean);
  }
}

静态工厂方式实例化

public class Bean2 {
}
public class MyBean2Factory {
   public static Bean2 createBean(){
       return new Bean2();
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="bean2" class="com.itheima.instance.static_factory.MyBean2Factory" factory-method="createBean"></bean>
</beans>
public class InstanceTest2 {
   public static void main(String[] args) {
       String xmlPath = "com/itheima/instance/static_factory/bean2.xml";
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
       Bean2 bean = (Bean2) applicationContext.getBean("bean2");
       System.out.println(bean);
  }
}

实例工厂方式实例化

public class Bean3 {
}
public class MyBean3Factory {
   public MyBean3Factory(){
       System.out.println("bean3工厂实例化中");
  }
   public Bean3 createBean(){
       return new Bean3();
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="myBean3Factory" class="com.itheima.instance.factory.MyBean3Factory"></bean>
   <bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean"></bean>
</beans>
public class InstanceTest3 {
   public static void main(String[] args) {
       String xmlPath = "com/itheima/instance/factory/bean3.xml";
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
       Bean3 bean = (Bean3) applicationContext.getBean("bean3");
       System.out.println(bean);
  }
}
posted @ 2022-03-08 15:45  阳光真好的博客  阅读(43)  评论(0)    收藏  举报