我们如何在Web应用程序中实例化Springbean
在我所看到的大多数spring教程中,Springbean的实例化类似于下面使用我们如何在Web应用程序中实例化Springbean,spring,Spring,在我所看到的大多数spring教程中,Springbean的实例化类似于下面使用main方法的类。但在现实世界中,这不是它的工作原理,对吗?比如说,在一个web应用程序的情况下,我们如何做下面的工作,我们需要做什么 ApplcationContext context = new ClassPathXmlApplicationContext("applicaitonContext.xml"); context.getBean("blah"); 使用spring的Web应用程序通常在Web.xml
main
方法的类。但在现实世界中,这不是它的工作原理,对吗?比如说,在一个web应用程序的情况下,我们如何做下面的工作,我们需要做什么
ApplcationContext context = new ClassPathXmlApplicationContext("applicaitonContext.xml");
context.getBean("blah");
使用spring的Web应用程序通常在
Web.xml
中定义了一个称为listener的小东西,如下所示:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
但这并不是春天的意义所在。您应该使用@Autowired
或@inject
注入“blah”bean,而不是直接与应用程序上下文交互
有关详细信息,请参阅spring
@Component
class AnyBean {
@Autowired
private ApplicationContext context;
void doSomethingWithBlah() {
context.getBean("blah").doSomething();
}
}