您的位置:首页 > 编程语言 > Java开发

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

2015-04-27 17:26 267 查看
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默认是使用类名的驼峰方式,当然也可以在注解处显示指定名称。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐