spring bean

下面是记录在spring当中,获取bean的方法并且

在spring mvc当中,spring把bean以annotation的方式的展现,并且分成4种@Controller,@Respository,@Service,@Component.

如何取得这些bean呢?

  • 首先要让系统知道bean,这个可以通过spring的自动扫描机制来完成 <context:component base-package=“test”></context:component> 这个就会自动扫描test包下面包含上面四种注释的类,并注入bean。
    在spring中,我们可以通过@Autowired来注入这些bean.但是在前台页面中,要如何获取这些bean呢?这时候我们可以使用WebApplicationContextUtils这个工具类来获取

    • 代码如下

      ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext();
      context.getBean("beanId");
      
    • 要正常使用这些工具类,需要在web.xml中加入配置信息

      <listener>
          <listener-class>
              org.springframework.web.context.ContextLoaderListener
          </listener-class>
      </listener>
      
原文地址:https://www.cnblogs.com/popping57/p/3405496.html