一 问题提出
当使用反射机制,会使得类中注入对象为空,注入失效。
二 解决方式
使用Spring的ApplicationContext可以解决注入失败问题。
三 代码
1 工具类
/**
* Copyright (C), 2020-2020, 软件公司
* FileName: ApplicationContextHelper.java
* Author: cakin
* Date: 2020/8/5
* Description: 获取环境中的bean
*/
package com.project.common.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
/**
* @className: ApplicationContextHelper
* @description: 获取环境中的bean
* @date: 2020/8/5
* @author: cakin
*/
@Service
public class ApplicationContextHelper implements ApplicationContextAware {
/**
* 应用上下文
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
/**
* 获取bean
*
* @param clazz bean所属的类
* @return T 返回的bean
*/
public static <T> T popBean(Class<T> clazz) {
//先判断是否为空
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(clazz);
}
/**
* 获取bean
*
* @param clazz bean所属的类
* @param name bean的name
* @return T 返回的bean
*/
public static <T> T popBean(String name, Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(name, clazz);
}
}
2 PersonInvoiceServiceImpl类
/**
* Copyright (C), 2020-2020, 软件公司
* FileName: PersonInvoiceServiceImpl.java
* Author: cakin
* Date: 2020/7/24
* Description: 实现类
*/
// 如果使用反射,PersonInvoiceServiceImpl注入personInvoiceDao会失败
@Service
public class PersonInvoiceServiceImpl extends BaseServiceImpl<PersonInvoice> implements PersonInvoiceService {
Logger logger = LogManager.getLogger(this.getClass());
@Autowired
private PersonInvoiceDao personInvoiceDao; // 通过反射机制,这里是无法注入成功的,因为反射是动态生成的,在系统初始化时,没法完成注入
public boolean updatePersonInvoice(PersonInvoice personInvoice) {
PersonInvoice oldPersonInvoice = personInvoiceDao.findOne(personInvoice.getId());
if (oldPersonInvoice != null) {
try {
MyBeanUtils.copyBeanNotNull2Bean(personInvoice, oldPersonInvoice);
} catch (Exception e) {
e.printStackTrace();
}
oldPersonInvoice.setUpdateTime(new Date());
personInvoiceDao.saveAndFlush(oldPersonInvoice);
logger.debug(oldPersonInvoice.toString());
return true;
} else {
logger.error("data doesn't exist:" + personInvoice.toString());
return false;
}
}
3 调用点
Class className = Class.forName(CLASSNAME);
personInvoiceService = (PersonInvoiceServiceImpl) ApplicationContextHelper.popBean("com.project.service.impl.PersonInvoiceServiceImpl"); // 获得系统初始化时注入的bean
personInvoiceService.updatePersonInvoice(personInvoice); // 这样就可以调用PersonInvoiceServiceImpl中的方法updatePersonInvoice,因为方法中的personInvoiceDao在系统初始化时就已经注入了,不会出现无法注入问题