通过Spring实现JavaBean的注入
需求:通过配置文件, 实现注入JavaBean,从而获取到xml文件中的Value值。
实现方式:
1.xml的配置。
在resource目录下,DispatcherServlet-servlet.xml中写我们需要注入的javabean。如图所示:
解释:我们定义一个webAppVersion,然后指定其类型为String。然后通过标签来实现Value的注入。标签意思是通过构造函数的方式来进行注入。
2.Java代码实现
importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.context.WebApplicationContext;
@RestController
@RequestMapping(path= "/info")public classVersionController {private Logger logger =LoggerFactory.getLogger(getClass());
@AutowiredprivateWebApplicationContext webAppContext;
@RequestMapping(path= "/getVersion", method =RequestMethod.GET)publicString getVersion() {
logger.info("mVTM version is " + webAppContext.getBean("webAppVersion").toString());return webAppContext.getBean("webAppVersion").toString();
}
}
解释:通过WebApplicationContext来实现自动注入。然后通过webAppContext.getBean("webAppVersion").toString()来拿到我们在xml中所配置的Value值。
3.特别注意。
由于我们在项目中使用的注解的方式来读取配置,所以我们一定要在DispatcherServlet-servlet.xml中,开启注解扫描。不然我们的注解是不会生效的。
谢谢大家。有问题请留言,大家共同学习!