首页>代码>Spring容器解析applicationContext.xml,提供bean的三种实例化用法(直接调用,静态工厂,实例工厂)>/源码-Spring容器(bean容器)通过解析applicationContext.xml,提供bean的三种用法(直接调用,静态工厂,实例工厂)/normal/Test.java
package ioc.myPoint.normal;
import module.model.User;
import module.service.UserService;
import module.serviceImpl.UserServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
/**
* 刚刚配置了spring的配置文件,src/applicationContext_userBean.xml
* 验证spring框架是否帮我们注入了bean
* 在我们的web程序中,用spring来管理各个实例(bean), 有时在程序中为了使用已被实例化的bean, 通常会用到这样的代码:
* 会带来一个问题:因为它会重新装载applicationContext-common.xml并实例化上下文bean, 如果有些线程配置类也是在这个配置文件中,那么会造成做相同工作的的线程会被启两次。一次是web容器初始化时启动,另一次是上述代码显示的实例化了一次。这在业务上是要避免的。
* @methodName: testIOC
* @description:
* @param
* @return void
* @throws
# @eg:
*/
public static void test(){
User user = new User();
user.setId(1);
//存疑?配置文件的路径配置
// String xmlPath = "WebRoot/applicationContext_userBean.xml";//读取不到
// String xmlPath = "classpath:META-INF/springConfig/applicationContext_userBean.xml";//不可以读取
// String xmlPath = "/applicationContext_userBean.xml"; //可以读取
String xmlPath = "ioc/myPoint/normal/applicationContext_userBean.xml";//可以读取
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) context.getBean("UserService");
//验证反射生成的类是不是属于 Userservice
boolean flg = userService instanceof UserServiceImpl;
boolean flg2 = userService instanceof UserService;
System.out.println("get到bean 和 本身的类是相同类型吗:"+flg);
System.out.println("get到bean 和 父类是相同类型吗:"+flg2);
userService.addUser(user);
}
/**
* 解决方法:不用类似new ClassPathXmlApplicationContext()的方式,从已有的spring上下文取得已实例化的bean。
* XXX 待实现
* @methodName: testIOC2
* @description:
* @param
* @return void
* @throws
# @eg:
*/
public static void testBeanmap(){
String xmlPath = "/applicationContext_userBean.xml";//可以读取
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
System.out.println( context.getBean("UserService") );
}
public static void main(String[] args) {
test();
// testBeanmap();
}
}
最近下载更多
lichangliu1098 LV12
2018年4月22日
朝鲜飞行员 LV7
2018年3月16日
zhengmingzhao LV1
2016年9月13日
chenxh LV1
2016年9月9日
panxia LV5
2016年8月30日
最近浏览更多
2636804923 LV6
2024年6月16日
aqin_qin LV1
2022年6月5日
jimshao289015254 LV9
2021年12月31日
水光浮藻 LV6
2021年3月25日
jeep123456 LV10
2021年3月17日
sanqijiang LV3
2020年10月25日
13043860zj LV16
2020年9月3日
fate02
2020年6月4日
暂无贡献等级
付洋麟 LV5
2020年5月15日
sweetyy LV8
2020年4月2日

