Spring教程
作者: 时海 hadoop迷
创建Bean

spring创建bean的方法有以下几种:完全依赖Spring框架创建、使用工厂类方法、使用工厂实例方法

1、完全依赖Spring框架创建bean

这也是最简单,最常用的方法:

<?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="myBean" class="spring.example.MyBean">
    </bean>
</beans>

2、使用工厂类方法

application.xml

<?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="mybean" factory-method="createBean" class="spring.example.BeanCreater">
    </bean>
</beans>
工厂类方法:
package spring.example;

public class BeanCreater {
    public static MyBean createBean(){
        return new MyBean();
    }
}

主类:

package spring.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        MyBean mybean1 = context.getBean("mybean", MyBean.class);
        MyBean mybean2 = context.getBean("mybean", MyBean.class);
        System.out.println(mybean1 == mybean2);
        //output: true
    }
}

注意:返回结果为true,程序打印的日志显示为cached singleton bean

11:20:46.318 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'mybean'

3、使用工厂实例方法

该方法先创建工厂实例,然后指定实例方法用于创建Bean

application.xml

<bean id="beanCreater" class="spring.example.BeanCreater">
</bean>
<bean id="mybean" factory-method="createBean" factory-bean="beanCreater">
</bean>

工厂类:

package spring.example;

public class BeanCreater {
    public MyBean createBean() {
        return new MyBean();
    }
}

主类:

package spring.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        MyBean mybean1 = context.getBean("mybean", MyBean.class);
        MyBean mybean2 = context.getBean("mybean", MyBean.class);
        System.out.println(mybean1 == mybean2);
        //output: true
    }
}





一个创业中的苦逼程序员
  • 回复
隐藏