Spring 获取 WebApplicationContext 常用方法

ClassPathXmlApplicationContext

  • 获取Spring容器(ApplicationContext)的方式有很多,比如常见的有如下所示:

ContextLoader获取

  • Java Web项目时可以常见的有如下所示:

import com.lct.service.ClientService;
import com.lct.service.ResourceService;
import com.lct.thread.ResourceProcessThread;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.net.*;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * Created by Administrator on 2018/3/27 0027.
 * UDP工具类
 */
public class UDPUtils {
    /**udpListenPort:下载文件的客户端监听的Udp端口
     * resourceService:随着类的工具类的加载而一次性赋值给它,之后直接传入到ResourceProcessThread中去做操作
     */
    private static final Integer udpListenPort;
    private static final Integer serverUdpListenPort;
    private static ResourceService resourceService;
    private static ClientService clientService;
    static {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("systemConfig");
        String udpListenPortStr = resourceBundle.getString("udpListenPort");
        String serverUdpListenPortStr = resourceBundle.getString("serverUdpListenPort");

        if (StringUtils.isNotBlank(udpListenPortStr)) {
            udpListenPort = Integer.parseInt(udpListenPortStr);
        } else {
            udpListenPort = 6789;
        }
        if (StringUtils.isNotBlank(serverUdpListenPortStr)) {
            serverUdpListenPort = Integer.parseInt(serverUdpListenPortStr);
        } else {
            serverUdpListenPort = 6757;
        }
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        resourceService = (ResourceService)webApplicationContext.getBean("resourceServiceImpl");
        clientService = (ClientService)webApplicationContext.getBean("clientServiceImpl");
    }


猜你喜欢

转载自blog.csdn.net/wangmx1993328/article/details/80401225
今日推荐