通過Spring實現JavaBean的注入
需求:通過配置文件, 實現注入JavaBean,從而獲取到xml文件中的Value值。
實現方式:
1.xml的配置。
在resource目錄下,DispatcherServlet-servlet.xml中寫我們需要注入的javabean。如圖所示:
<bean id="webAppVersion" class="java.lang.String"> <constructor-arg value="V2.1.1.20171227_alpha"/> </bean>
解釋:我們定義一個webAppVersion,然后指定其類型為String。然后通過<constructor-arg>標簽來實現Value的注入。<constructor-arg>標簽意思是通過構造函數的方式來進行注入。
2.Java代碼實現
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; @RestController @RequestMapping(path = "/info") public class VersionController { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private WebApplicationContext webAppContext; @RequestMapping(path = "/getVersion", method = RequestMethod.GET) public String 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中,開啟注解掃描。不然我們的注解是不會生效的。
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="你要掃描的包"></context:component-scan>
謝謝大家。有問題請留言,大家共同學習!