使用@Component时再使用@Resource或@Autowired时注入失败问题

使用@Component时再使用@Resource或@Autowired时注入失败问题

情景:最近在写MQ时发现在使用了@Component同时使用@Autowired自动注入service的时候发现并未注入成功,得到的对象是null
使用@Component时再使用@Resource或@Autowired时注入失败问题_第1张图片
原因
在使用@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注解放在方法上会在类加载后自动注入这个方法的参数,并执行一遍方法。

你可能感兴趣的:(使用@Component时再使用@Resource或@Autowired时注入失败问题)