spring@value加载时机

@value是spring中一个用来注入类的成员变量的一种注解,其从配置文件中注入配置的值,需要在spring中配置下需要注入这个类PropertyPlaceholderConfigurer,有多种出入方式,如:

 

<bean id="propertyConfigurer" class="PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:config/*.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="fileEncoding" value="UTF-8"/>
	</bean>
 @Value注入是在spring注入该类的默认构造器之后,再进行注入的。

 


使用org.springframework.beans.BeanUtils的public static <T> T instantiateClass(Constructor<T> ctor, Object... args)进行实例化@Component的类。使用这个bean工厂DefaultListableBeanFactory。

使用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)来创建这个bean的实例,mbd中是一些类似这样的数据:

scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null

默认情况下spring管理的bean都是单例。
实例构造完成之后,这个时候@Value注解就会触发,org.springframework.beans.factory.annotation。AutowiredAnnotationBeanPostProcessor的inject(Object bean, String beanName, PropertyValues pvs)这个方法就会将bean的属性注入进去了。注入属性完成后(下图第557行),spring再去加载其他的bean。@Value其实也是使用了@AutoWire的机制。

 由于spring只会在初始化时,加载这个类的构造器,如果需要修改配置文件中的值,可以通过spring上下文获取bean实例,使用set方式修改值。@Value加载中文时出现乱码,可以在PropertyPlaceholderConfigurer配置编码格式,上文的code中有调到,也可将中文改成unicode编码。

猜你喜欢

转载自cc-weige.iteye.com/blog/2381000