在Spring-MVC中如何检索bean?

时间:2019-05-10 07:20:07

标签: java spring spring-mvc

在一个简单的spring应用程序中,您使用@Component批注将bean注册到spring IoC容器中,然后要检索该bean,首先要读取spring配置文件,然后使用以下方法从容器中检索bean:

ClassPathXMLApplicationContext context = new ClassPathXMLApplicationContext("spring config file")


Coach theCoach=context.getBean("beanId","classname") 

现在,您可以在theCoach上调用方法了。

由于不使用

,我们如何从容器中检索Bean?
context.getBean();

DispatcherServlet正在处理吗?

编辑后-

/ *********************春季申请*********************** ******** / applicationContext.xml

<beans _______>

<context:component-scan base-package="packageName"/>

</beans>

Coach.java

public interface Coach{

public String getDailyWorkOut();

}

TennisCoach.java

@Component                                                                                                   

public class TennisCoach implements Coach{

public String getDailyWorkOut(){

return "practise back hand volley"; 

}

ApplicationDemo.java

public class ApplicationDemo{

public static void main(String[] args){

ClassPathXMLApplicationContext context = new ClassPathXMLApplicationContext("applicationContext.xml");

Coach theCoach=context.getBean("tennisCoach",Coach.class)

theCoach.getDailyWorkOut();

}

}

/ *********************春季申请*********************** ******** /

现在使用Spring MVC-

/*****************Spring-MVC Application**************************/

web.xml

<web-app>
<servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigurationLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
</servlet>

    <servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

applicationContext.xml

<beans _______>

<context:component-scan base-package="packageName"/>

</beans>

Coach.java

public interface Coach{

public String getDailyWorkOut();

}

TennisCoach.java

@Component                                                                                                   

public class TennisCoach implements Coach{

@RequestMapping("/")
public String getDailyWorkOut(){

return "practise back hand volley"; 

}
/*********************Spring-MVC Application*********************/

我想知道的是-

在上述给定的Spring应用程序中,我正在使用context.getBean()从容器中检索bean,如何在Spring-MVC应用程序中检索Coach bean?

2 个答案:

答案 0 :(得分:0)

是的,您可以创建带有@Autowired批注的字段,然后为您自动注入。确保将要使用此bean的类也是spring bean。

答案 1 :(得分:0)

在您的示例中,您是通过 bean查找ApplicationContext检索bean。

Coach theCoach=context.getBean("tennisCoach",Coach.class)

在这种情况下,您知道所需的确切类名(例如,您是bean的作者),并且只需从上下文中获取它即可。


对于DispatcherServlet来说并不是那么容易,因为它对您添加到上下文中的bean一无所知。

它唯一的选择是对上下文Bean中定义的所有对象进行全面扫描,并检测它可以识别的任何内容(ControllerRestControllerRequestMapping)。这类 detector 的示例是AbstractDetectingUrlHandlerMapping及其实现。 SpringMvc具有此类检测器的各种实现,您可以根据需要实现自己的实现。