Spring 读取配置文件(二)

Spring 读取配置文件并调用 bean

package cn.com.test.receive;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationInitialize {
    
    @Value("${tms.terminal.search:200}")
    private int search;

    @Value("${tms.terminal.monitor:15}")
    private int monitor;

    @Value("${tms.terminal.signkey:POI:}")
    private String signkey;
    
    @Value("${tms.terminal.queueName:gps}")
    private String queueName;
    
    @Value("${tms.terminal.exchangeName:tms}")
    private String exchangeName;
    
    @Value("${tms.terminal.routingKey:tms}")
    private String routingKey;
    
    @Bean
    public ConsumerService consumerService() {
        try {
            ConsumerService consumerService = new ConsumerService(search,monitor,signkey,queueName,exchangeName,routingKey);
            return consumerService;
        } catch (Exception e) {
            // TODO: handle exception
            throw e;
        }
    }
    
    @Bean
    public ProducerAgent producerService() {
        try {
            ProducerAgent producerAgent = new ProducerAgent();
            return producerAgent;
        } catch (Exception e) {
            // TODO: handle exception
            throw e;
        }
    }
}

package cn.com.test.receive;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.evun.tms.entity.QueueMessages;

/***
 * 消费者
 * @author 
 *
 */
public class ConsumerService {
    
    private static final Logger logger = LoggerFactory.getLogger(ConsumerService.class);
    
    protected int SEARCH_COUNT;
    protected String SIGN_KEY;
    protected long MONITOR_SECONDS;
    protected String QUEUE_NAME;
    protected String EXCHANGE_NAME;
    protected String ROUTING_KEY;
    
    
    /***
     * 初始化消费者
     * @param search
     * @param monitor
     * @param signkey
     * @param queue_name
     */
    public ConsumerService(int search,int monitor,String signkey,String queue_name,String exchangeName,String routingKey) {
        SEARCH_COUNT = search;
        MONITOR_SECONDS = monitor;
        SIGN_KEY = signkey;
        QUEUE_NAME = queue_name;
        EXCHANGE_NAME = exchangeName;
        ROUTING_KEY = routingKey;
    }

    /**
     * 启动服务消费者
     * @throws Exception 
     */
    public void Start() throws Exception {
        // TODO Auto-generated method stub
        try {
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("-----------------------------    Start: "+ e.getMessage() +"    -----------------------");
            throw e;
        }
    }
}

package cn.com.test.receive;

import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Spring 注入初始化配置文件资源
 * @author 
 *
 */
public class ConfigurationBase {
    
    private static final Logger logger = LoggerFactory.getLogger(ConfigurationBase.class);
    
    /***
     * Spring 自动注入扫描加载  @Configuration 注解标识的类
     *               及调用 ConfigurationBase.class.getResourceAsStream 加载配置文件
     * 并载入 @Bean 等相关注解标注的 javaBean
     * @param resource
     * @param basePackages
     * @return
     */
    public SuperAnnotationConfigApplicationContext loadSpringContext(String resource,String... basePackages) {
        try {
            this.loadConfigurationFromResource(resource);
            //this.setSystemProperties();
            return new SuperAnnotationConfigApplicationContext(basePackages);
        } catch (Exception e) {
            // TODO: handle exception
            throw e;
        }
    }
    
    /**
     * 加载应用程序配置文件
     * @param resource
     */
    private void loadConfigurationFromResource(String resource) {
        InputStream is = ConfigurationBase.class.getResourceAsStream(resource);
        try {
            if (is != null) {
                System.getProperties().load(is);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
    
    @SuppressWarnings("unused")
    private void setSystemProperties() {
        System.setProperty("redis.keys.group", "cn.com.redis.test.case");
    }
    
    /**
     * 通过应用上下文,初始化类参数
     * @author
     *
     */
    public class SuperAnnotationConfigApplicationContext extends AnnotationConfigApplicationContext {
        
        public SuperAnnotationConfigApplicationContext(String... basePackages) {
            super();
            GenericBeanDefinition gbd = new GenericBeanDefinition();
            gbd.setBeanClass(PropertyPlaceholderConfigurer.class);
            this.registerBeanDefinition("propertyPlaceholderConfigurer", gbd);
            this.scan(basePackages);
            this.refresh();
        }
    }
}

/**
*
* 实例化调用
*/
private static void runClient() throws Exception{ try { ConfigurationBase configurationBase = new ConfigurationBase(); SuperAnnotationConfigApplicationContext applicationContext = configurationBase.loadSpringContext("/terminal-receive.properties", "cn.com.test.receive"); ConsumerService consumerService = (ConsumerService) (applicationContext.getBean("consumerService")); consumerService.Start(); } catch (Exception e) { // TODO: handle exception throw e; } }

terminal-receive.properties

# tms redis count
tms.terminal.search=200
# tms monitor
tms.terminal.monitor=15
# redis signkey
tms.terminal.signkey=POI:
# rabbit mq queueName
tms.terminal.queueName=gps
# rabbit mq exchangeName
tms.terminal.exchangeName=tms
# rabbit mq routingKey
tms.terminal.routingKey=tms
原文地址:https://www.cnblogs.com/rinack/p/6054158.html