使用@Component时再使用@Resource或@Autowired时注入失败问题
情景:最近在写MQ时发现在使用了@Component同时使用@Autowired自动注入service的时候发现并未注入成功,得到的对象是null

原因:
在使用@Component注解将bean实例化到spring容器内的时候,@Autowired是在这个bean之中的,@Autowired还未完成自动装载,所以导致service为null
解决方法:
@Component
public class MsgReceiver {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
// @Autowired
// private EmployeeServer employeeServer;
// @Autowired
// private AttendanceinfoServer attendanceinfoServer;
// @Autowired
// private RedisService redisService;
private static EmployeeServer employeeServer;
private static RedisService redisService;
private static AttendanceinfoServer attendanceinfoServer;
@Autowired
public void setEmployeeServer(EmployeeServer employeeServer) {
MsgReceiver.employeeServer = employeeServer;
}
@Autowired
public void setRedisService(RedisService redisService) {
MsgReceiver.redisService = redisService;
}
@Autowired
public void setRedisService(AttendanceinfoServer attendanceinfoServer) {
MsgReceiver.attendanceinfoServer = attendanceinfoServer;
}
}
原因:
@Autowired注解放在方法上会在类加载后自动注入这个方法的参数,并执行一遍方法。
当在Spring中使用@Component的同时,@Resource或@Autowired注解无法正常注入服务,导致对象为null。原因是@Bean实例化发生在@Autowired之前,因此服务未被正确装配。解决方法是将@Autowired注解放在方法上,以便在类加载后自动注入并执行方法。
995

被折叠的 条评论
为什么被折叠?



