实例化bean

常规方式

  1. 通过构造器(xml、java注解、java api)
  2. 通过静态工厂方法(xml、java api)
    如:
<!-- 静态方法实例化 Bean,在User类中定义静态方法 createUser -->
<bean id="user-by-static-method" class="spring.ioc.overview.domain.User"
          factory-method="createUser"/>
  1. 通过Bean工厂方法(xml、java api)
    如:
<!-- 实例(Bean)方法实例化 Bean -->
<bean id="user-by-instance-method" factory-bean="userFactory" factory-method="createUser"/>
    
<bean id="userFactory" class="spring.bean.factory.DefaultUserFactory"/>
public interface UserFactory {
    default User createUser() {
        return User.createUser();
    }
}
// 默认工厂实现
public class DefaultUserFactory implements UserFactory{
}
  1. 通过FactoryBean(xml、java注解、java api)
<!-- FactoryBean实例化 Bean -->
<bean id="user-by-factory-bean" class="spring.bean.factory.UserFactoryBean" />
// 实现spring的FactoryBean接口
public class UserFactoryBean implements FactoryBean {

    @Override
    public Object getObject() throws Exception {
        return User.createUser();
    }

    @Override
    public Class<?> getObjectType() {
        return User.class;
    }
}

特殊方式

  1. 通过ServiceLoaderFactoryBean(xml、java注解、java api)
    如:
<bean id="userFactoryServiceLoader" class="org.springframework.beans.factory.serviceloader.ServiceLoaderFactoryBean">
	<!-- UserFactory 工厂接口 -->
	<property name="serviceType" value="spring.bean.factory.UserFactory" />
</bean>
ServiceLoader<UserFactory> serviceLoader = beanFactory.getBean("userFactoryServiceLoader", ServiceLoader.class);
Iterator<UserFactory> iterator = serviceLoader.iterator();
while (iterator.hasNext()) {
     UserFactory userFactory = iterator.next();
     System.out.println(userFactory.createUser());
}
  1. 通过AutowireCapableBeanFactory#createBean(class, int, boolean)
  2. 通过BeanDefinition#registerBeanDefinition(String, BeanDefinition)

初始化bean

初始化bean阶段回调方式:

  1. @PostConstruct标记方法
  2. 实现InitializingBean 接口的 afterPropertiesSet()方法
  3. 自定义初始化方法
    xml配置:<bean init-method=“init” …/>
    java注解:@Bean(initMethod = “init”)
    java api:AbstractBeanDefinition#setInitMethodName(String)

如,在某个bean上配置:

public class DefaultUserFactory implements InitializingBean {

    // 基于 @PostConstruct 注解
    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct : UserFactory 初始化中...");
    }

    public void initUserFactory() {
        System.out.println("自定义初始化方法 initUserFactory() : UserFactory 初始化中...");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean#afterPropertiesSet() : UserFactory 初始化中...");
    }
}

三种顺序依次是:1 > 2 > 3