Spring: how to get hold of Application context in Webapp and Standalone program

后端 未结 1 1468
野的像风
野的像风 2021-02-04 18:29

I\'m new to the Spring Framework. We want to introduce it (3.1) in a web application, currently using struts in the web layer, service facades and business objects in the busine

相关标签:
1条回答
  • 2021-02-04 18:58
    1. It's very common that one let spring handle the lifecycle of all the beans, otherwise it might get a bit tricky. The objects that are not spring beans are hopefully initialized somewhere. Make that initializer a spring bean and make it application context aware

       public class SpringContextHolder implements ApplicationContextAware {
      
         private static ApplicationContext applicationContext = null;
      
          public static ApplicationContext getApplicationContext() {
              return applicationContext;
          }
          public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
               this.applicationContext = applicationContext;
          }
          public void init(){
      
              ServiceBean1 srv1 = (ServiceBean1)applicationContext.getBean("serviceBean1");
      
              myNonSpringObject.setService1(srv1); // Or something
          }
      }
      
    2. Setting up a standalone spring app is very easy. Just create a Spring XML and wire your beans (either via scanning/annotations or XML). It is not really recommended to do this in the main method, but you could easily figure out how to get this setup in your standalone application. Keep in mind that your application itself should not really do much lifecycle logic but let Spring do that.

      public class StandaloneSpringApp{
        public static void main(String[] args){
          ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
      
          SomeBeanType bean = (SomeBeanType)ctx.getBean("SomeBeanName");
          bean.doProcessing(); // or whatever
        }
      
      }
      
    3. Your setup makes perfect sense, even though I cannot visualize your entire scope, your approach is a good starting point for a large modularized spring application.

    0 讨论(0)
提交回复
热议问题