spring注解时,如何手工获取bean
2015-04-27 17:26
267 查看
1、当我们的组件使用注解进行注入的时候,我们同样可以使用WebApplicationContextUtils 来获取对应的bean,名字默认是类名的驼峰格式(也可以在注解处显示指定名称)。
例如在listener中,可以通过下面的方式获取bean
1.监听器:
注:
1.listener的顺序必须在spring的contextLaoderListener之后;
2.service位置必须可以让spring扫描到;
2、quartz中使用spring注解的bean
1.xml
2.service
例如在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默认是使用类名的驼峰方式,当然也可以在注解处显示指定名称。
相关文章推荐
- quartz如何获取spring注解注入的bean
- spring利用扫描方式对bean的处理(对任何版本如何获取xml配置信息的处理)
- 如何手动获取Spring容器中的bean(ApplicationContextAware 接口)
- SpringBoot普通类中如何获取其他bean例如Service、Dao
- Spring 关于bean的获取以及自定义注解的起始注入和获取
- Spring启动后获取所有拥有特定注解的Bean
- Java中如何获取Spring中配置的bean
- spring 如何动态的获取bean
- 反射创建的bean,如何在Spring中获取
- 单元测试使用spring注解获取bean
- 重温Spring之旅3——装配Bean(手工装配:使用注解方式)
- Spring 注解中,普通类获取@Service标记的方法 或者bean对象
- 如何在线程中获取spring 管理的bean
- [原创]java WEB学习笔记98:Spring学习---Spring Bean配置及相关细节:如何在配置bean,Spring容器(BeanFactory,ApplicationContext),如何获取bean,属性赋值(属性注入,构造器注入),配置bean细节(字面值,包含特殊字符,引用bean,null值,集合属性list map propert),util 和p 命名空间
- spring源码分析(web)--通过注解获取bean源码分析
- 如何在自定义标签中获取spring通过@Service注解来的service
- Spring如何管理Java普通类(Java类获取Spring容器的bean)
- 代码获取Spring注解的bean
- Spring 如何读取 Bean 的注解信息
- Spring+Servlet整合(如何向Servlet注入属性(转),servlet获取spring容器中的bean)