InitializingBean接口为Bean提供了初始化的方法,它只包含afterPropertiesSet方法,在初始化bean的时候会执行该办法。
Spring为bean提供了两种初始化的方式:一、实现InitializingBean接口,实现afterPropertiesSet方法。二、在配置文件中通过init-method指定初始化方法。
我们来看下这两种初始化的方式有什么区别
package cn.com.tool.command;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class StartCommand implements InitializingBean{
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("java代码中初始化start");
}
public void init() {
System.out.println("配置文件中初始化start");
}
}
在Spring容器配置文件添加
<bean id = "startCommand" class="cn.com.tool.command.StartCommand" init-method="init"></bean>
启动Spring容器观察日志打印
通过日志打印顺利我们可以知道 第一种方式优先于第二种