通过Spring实现JavaBean的注入

通过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>

谢谢大家。有问题请留言,大家共同学习!

原文地址:https://www.cnblogs.com/Edward-Wang/p/8134136.html