小弟初学Spring,有一个问题纠结了很久没解决,废话不多说,进入正题
我配置好了Spring的XML文件:applicationContext.xml,注入一切都是正常的。但是具体调用那些bean的时候,我要是用
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) factory.getBean("userService");
userService.getPassWordByUserName("wewe");
这样的方法完全可以,但是问题是。我现在要启动了tomcat,让bean在tomcat中创建好了,我该怎么调用那些bean?
不要用BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");这种方法了,这种方法只会再次加载一遍applicationContext.xml。我要调用tomcat中已经创建的现成的bean。
求指教!!
我配置好了Spring的XML文件:applicationContext.xml,注入一切都是正常的。但是具体调用那些bean的时候,我要是用
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) factory.getBean("userService");
userService.getPassWordByUserName("wewe");
这样的方法完全可以,但是问题是。我现在要启动了tomcat,让bean在tomcat中创建好了,我该怎么调用那些bean?
不要用BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");这种方法了,这种方法只会再次加载一遍applicationContext.xml。我要调用tomcat中已经创建的现成的bean。
求指教!!
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
让tomcat 给你家在
ServletContext servletContext = this.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
***Bean bean = (***Bean)ctx.getBean("beanName");
ServletContext servletContext = this.getServletContext(); 会报错,其中的this是什么?
在Web.xml中配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext
(this.getServletContext());
Integer ing = (Integer) ctx.getBean("random");
System.out.println(ctx.getBean("random"));