启动spring容器几种方法

1 spring通过对Junit框架的整合功能来启动Spring非Web容器(推荐)

junit测试方法时使用:需要引入junit4、spring的jar包、spring-test.jar


            junit
            junit
            test
        
        
            org.springframework
            spring-test
            test
        


    org.springframework
    spring-context
    5.1.3.RELEASE

代码:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration({"classpath:spring-config.xml"})  
public class TestBeanImplTest {  
    @Resource TestBean testBean;  
      
    @Test  
    public void getBeanTest(){  
        
          system.out.print(testBean);
    }  
}  

 

2.在main方法中初始化spring容器:

public class TestBeanImpl{  
      
    public  static void main(String[] args){  
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");  
  
        context.start();  
  
        TestBean test= (TestBean) context.getBean("testBean");  
        System.out.println(test);  
    }  
      
} 

3.调用静态方法时初始化

package com.data.test;

import com.data.test.monitor.ServiceFacade;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @description: single
 * @author: feng
 * @create: 2018-12-21 17:49
 **/

public class SingleTest {

    public static Logger logger = org.slf4j.LoggerFactory.getLogger(SingleTest.class);

    private static SingleTest sin = new SingleTest ();

    public static ServiceFacade serviceFacade;

    private SingleTest (){
        logger.info("初始化Spring容器开始。");
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-config.xml");
        serviceFacade  =(ServiceFacade) ac.getBean("ebMonitorInnerServiceFacade");
        logger.info("获取bean-ServiceFacade:{}",serviceFacade );
    }

    public static SingleTest get(){
        return sin;
    }
}

4.web容器启动 

web.xml配置




    hotel

    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        contextConfigLocation
        classpath*:/spring-config.xml
    

    
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    

    
        CharacterEncodingFilter
        /*
    

    
    
        /index.html
    
    
    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath*:/spring-web.xml
        
        1
    

    
        DispatcherServlet
        /*
    




 

你可能感兴趣的:(初始化spring容器几种方法)