1不在启动类application所在包及其子包的类
这个可以在application中通过@ComponentScan加入
@Slf4j
@SpringBootApplication
@ComponentScan(basePackages = {"com.vmos.consumer", "com.vmos.common"})
public class KafkaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(KafkaConsumerApplication.class, args);
log.error("KafkaConsumerApplication --Start Success");
}
}
2 不是@Controller或@Service 或@Component标注类
无特殊意义使用 @Component 标注
@Slf4j
@Order(value = 5)
@Component
public class LogAdEventRunnable implements Runnable {
}
3、不属于1、2但是,变量是New出来的,也不会自动注入
如: LogAdEventRunnable eventLog = new LogAdEventRunnable();
则在当前类LogAdEventRunnable中,如果用了@Autowired注入其他对象,则这些变量会是空null。 你只能注入当前类然后调用这个类 不能new,或者直接this关键字使用当前类。
如果是采用@Autowired注入变量,则当前类的实例,必须也是spring 容器注入才能成功注入,应该也采用@Autowired注入,要不就不要new需要注入其他对象的当前类
@Component
@Order(value = 5)
public class consumerThreads implements CommandLineRunner {
// 定义一个常量线程池(定长为3的线程池)
private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(3);
@Autowired
LogAdEventRunnable logAdEventRunnable;
@Override
public void run(String... args) throws Exception {
//错误用法
EXECUTOR_SERVICE.submit(new LogAdEventRunnable());
//正确用法
EXECUTOR_SERVICE.submit(logAdEventRunnable);
EXECUTOR_SERVICE.submit(logAdEventRunnable);
EXECUTOR_SERVICE.submit(logAdEventRunnable);
/* LogAdEventRunnable ad = new LogAdEventRunnable();
ad.start();*/
}
--------------------------------------------------------------------------
注释: 错误用法导致 RedisService 自动注入失败
@Slf4j
@Order(value = 5)
@Component
public class LogAdEventRunnable implements Runnable {
@Autowired
private RedisService redisService;
}