+
 新版

springboot中,ContextLoader.getCurrentWebApplicationContext()获取的为Null

白云山中 发布于 2016/07/22 15:18
阅读 24K+
收藏 1

springboot版本:1.3.6.RELEASE

package com.pp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class App extends SpringBootServletInitializer {
	
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(App.class);
	}
	
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}



package com.pp;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ContextLoader;

@RestController
public class HomeController {

	@RequestMapping("/home")
	public String home(){
		System.out.println(ContextLoader.getCurrentWebApplicationContext());
		return "home";
	}
}



启动main方法之后(内嵌tomcat8),

System.out.println(ContextLoader.getCurrentWebApplicationContext());

输出为null

请问,哪里有问题?

加载中
0
烽火云烟
烽火云烟
用spring就要适应它的ioc控制反转,试试用@Autowired注解让spring自动注入ApplicationContext给你吧。
白云山中
白云山中
我知道这样可以。我就是想知道,ContextLoader.getCurrentWebApplicationContext()这样为啥不行,
0
学而不思则罔
学而不思则罔
不要用main函数的方式启动,使用下面maven命令方式启动试试?
spring-boot:run
白云山中
白云山中
不行,还是为null
0
学而不思则罔
学而不思则罔

另外推荐使用ApplicationContextAware的方式获取ApplicationContext,这样对非web及web环境都有很好的支持,我的工程这样写的:

@Component @Lazy(false) public class ApplicationContextRegister implements ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextRegister.class);   private static ApplicationContext APPLICATION_CONTEXT;   /**  * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException  */  @Override  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { LOGGER.debug("ApplicationContext registed-->{}", applicationContext);  APPLICATION_CONTEXT = applicationContext;  } public static ApplicationContext getApplicationContext() { return APPLICATION_CONTEXT;  }
}

蛋炒饭加个蛋
蛋炒饭加个蛋
非常感谢,我就是采用这个方法解决的,后来的朋友,代码可以直接拷贝过去,然后用ApplicationContextRegister.getApplicationContext() .getBean("xxservice");就可以获取对应的service了,学海无涯,感恩前辈们。
0
太猪-YJ
太猪-YJ

我也想知道答案

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部