Spring初始化,将配置文件properties注入到bean中

首先是Spring的配置文件

applicationContext.xml 

<!-- 打开注解 -->
	<context:annotation-config/>
	<!-- 扫描包,一定要扫描到相应的VO类 -->
	<context:component-scan base-package="com.ssh.*" />
    <!-- 加载properties文件,用于往javabean中注入 -->
	<bean name="myproperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    	<property name="locations">
    		<list>
    			<value>classpath:META-INF/app_config/properties/sysconfig.properties</value>
    			<value>classpath:META-INF/app_config/properties/sysconfig-debug.properties</value>
    		</list>
    	</property>
    </bean>
    <!-- 加载properties文件,用于替换Spring 配置文件中的占位符变量(${varible}) -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="properties" ref="myproperties"></property>
    	<property name="locations">
    		<list>
    			<value>classpath:META-INF/app_config/properties/global.framwork.properties</value>
    		</list>
    	</property>
    </bean>

 

SysConfigVo

package com.ssh.service;

import org.springframework.stereotype.Component;
import org.springframework.bean.factory.annotation.Value;

@Component
public class SysConfig {

	//myProperties必须和applicationContext.xml中的PropertiesFactoryBean的name一样
	@Value("#{myProperties}['gloable.model']")
	private String gloable_model;

	public String getGloable_model() {
		return gloable_model;
	}

	public void setGloable_model(String gloable_model) {
		this.gloable_model = gloable_model;
	}
	
}

 在service中使用该VO

package com.ssh.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ssh.dao.UserDao;
import com.ssh.entity.User;

@Service
public class UserService {

	@Resource
	private SysConfig sysConfig;
	logger.info(sysConfig.getGloable_model());
	
}

 

猜你喜欢

转载自javaxxxd.iteye.com/blog/2316630