spring中获取自定义的Bean

	public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
		DBSpringDao bean = context.getBean(DBSpringDao.class);
		//BeanFactory factory = context;
		//DBSpringDao bean = factory.getBean(DBSpringDao.class);
		String sql="select * from i_user";
		List<Map<String, Object>> list=bean.queryForList(sql);
	}

获取Bean的其他方式
注意 ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext 的区别

// 用classpath路径,不加classpath默认前缀
 ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

// ClassPathXmlApplicationContext使用了file前缀是可以使用绝对路径的
ApplicationContext context = new ClassPathXmlApplicationContext("file:F:/workspace/project/src/applicationContext.xml");

// 用文件系统的路径,默认指项目的根路径
ApplicationContext context = new FileSystemXmlApplicationContext("src/applicationContext.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("webRoot/WEB-INF/applicationContext.xml");


// 使用了classpath:前缀,这样,FileSystemXmlApplicationContext也能够读取classpath下的相对路径
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("file:F:/workspace/project/src/applicationContext.xml");

// 不加file前缀
ApplicationContext context = new FileSystemXmlApplicationContext("F:/workspace/project/src/applicationContext.xml");

为了避免重新装载applicationContext.xml并实例化上下文bean不用类似
new ClassPathXmlApplicationContext()的方式,从已有的spring上下文取得已实例化的bean。
首先创建一个工具类

//实现ApplicationContextAware
public class ApplicationContextUtil implements ApplicationContextAware {
 
	private  ApplicationContext context;//声明一个静态变量
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.context=applicationContext;
	}
 
	public  ApplicationContext getContext(){
		  return context;
	}
}

注入
springboot使用注解进行注入

//初始化并注入
<bean id="applicationContextUtil" class="com.service.utils.ApplicationContextUtil"></bean>
//业务类进行注入applicationContextUtil实例
<bean id="xxxx" class="com.service.xx.xx.xx" >
  <property name="appContextUtil" ref="applicationContextUtil" /> 
 </bean>

使用

 ApplicationContext context=appContextUtil.getContext();
 DBSpringDao bean = context.getBean(DBSpringDao.class);
 String sql="select * from i_user";
 List<Map<String, Object>> list=bean.queryForList(sql);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值