spring注解时,如何手工获取bean

1、当我们的组件使用注解进行注入的时候,我们同样可以使用WebApplicationContextUtils 来获取对应的bean,名字默认是类名的驼峰格式(也可以在注解处显示指定名称)。

例如在listener中,可以通过下面的方式获取bean

1.监听器:

public class ProjectInit implements ServletContextListener{
	private static Logger logger = Logger.getLogger(ProjectInit.class);
		
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.info("==========初始化信息进行销毁==========");
	}
	
	public void contextInitialized(ServletContextEvent arg0) {
		logger.info("==========系统初始化==========");
		try {
			ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext());
			InitService initService = (InitService) ctx.getBean("initServiceImpl");
			initService.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
2.service

@Service
@SuppressWarnings({ "rawtypes"})
public class InitServiceImpl  implements InitService {
	@Autowired
	private ReportDao reportDao;
	
	public void init() throws Exception {
		initReport();
	}
	
	private void initReport() throws Exception {
		Map param = new HashMap();
		List<Map> list = reportDao.select4MapParam(param, "queryReportQuery");
		ReportCache.setQueryReportList(list);
	}
}

1.listener的顺序必须在spring的contextLaoderListener之后;

2.service位置必须可以让spring扫描到;



2、quartz中使用spring注解的bean

1.xml

<!-- 自定义任务 -->
<bean id="exposureDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="adResourceServiceImpl"></property>
		<property name="targetMethod" value="executeExposure"></property>
		<property name="concurrent" value="false" />
		
</bean>


2.service

@Service
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AdResourceServiceImpl  implements AdResourceService {
	@Autowired
	private AdResourceDao adResourceIisDao;
	
xml中adResourceServiceImpl默认是使用类名的驼峰方式,当然也可以在注解处显示指定名称。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值