Spring中配置的bean是自动加载的,当类调用的时候实例化并返回调用者。
配置:
?xml version="1.0" encoding="UTF-8"?>
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
程序中获取bean的操作:
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
//判断两次请求singleton作用域的Bean实例是否相等
System.out.println(ctx.getBean("bean1")==ctx.getBean("bean1"));
//判断两次请求prototype作用域的Bean实例是否相等
System.out.println(ctx.getBean("bean2")==ctx.getBean("bean2"));
}
}
如果容器已经运行,在jsp与javabean中只要可以拿到request,可以这样
ServletContext context = req.getServletContext();
WebApplicationContext appContext =
WebApplicationContextUtils.getWebApplicationContext(context);
// 获得userService实例
UserService userService = (UserService)context.getBean("userService"); //userservice是spring配置文件中的bean 的ID
如果不能取到request可以这样
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"classpath:spring/spring-config.xml",
"classpath:spring/spring-mybatis.xml"});
UserService userService = (UserService)context.getBean("userService"); //userservice是spring配置文件中