Spring加载完毕时,初始化参数


三种方式:1、实现org.springframework.beans.factory.InitializingBean接口。

该接口实现其afterPropertiesSet方法,InitializingBean可以注入相关的service,如果在Spirng处理InitializingBean时出错,那么Spimport ring将直接抛出异常。
代码如下:



import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.symdata.common.core.LogUtils;
import cn.symdata.payment.liandong.LianDongConfig;
@Component
public class TestInit implements InitializingBean {
	
	@Autowired
	private LianDongConfig  config;

	@SuppressWarnings("rawtypes")
	@Override
	public void afterPropertiesSet() throws Exception {
		LogUtils.info(this.getClass(), "TestInit", "");
	 
	}

}





 2、使用@Autowired注解

@Autowired加在方法上,可以在spring加载完毕时自动执行,并且可以将用到的参数,自动注入

代码如下:

	@Autowired
	public void initFieldsValue(LianDongConfig config) {
		LogUtils.info(this.getClass,"initFieldsValue","");
	}




//参数LianDongConfig 可以自动注入

 3、配置init-method属性:
在需要进行操作的bean的xml定义中加上init-method属性,指定下启动时运行哪个方法

init-method是通过反射执行的,而afterPropertiesSet是直接执行的。所以 afterPropertiesSet的执行效率比init-method要高,不过init-method消除了bean对Spring依赖。在实际使用时我推荐使用init-method。

    需要注意的是Spring总是先处理bean定义的InitializingBean,然后才处理init-method。如果在Spirng处理InitializingBean时出错,那么Spring将直接抛出异常,不会再继续处理init-method。

    如果一个bean被定义为非单例的,那么afterPropertiesSet和init-method在bean的每一个实例被创建时都会执行。单例 bean的afterPropertiesSet和init-method只在bean第一次被实例时调用一次。大多数情况下 afterPropertiesSet和init-method都应用在单例的bean上。







你可能感兴趣的:(java,spring)