@Autowired实体为空

时间:2019-04-26 10:56:04

标签: spring spring-boot jcommander

@Component
public class TempTry implements CommandLineRunner{

@Autowired
TokenRepository tkeRepo;

@Parameter(names = { "--email", "-e" })
String email;

static final Logger logger = LoggerFactory.getLogger(TempTry.class);

@Override
public void run(String... args) throws Exception {
    logger.info("ApplicationStartupRunner run method Started !!");
    TempTry main = new TempTry();
    JCommander.newBuilder().addObject(main).build().parse(args);
    main.runtask();
}

public void runtask() {

    LocalDateTime expiryTime = LocalDateTime.now().plusDays(1);
    String uuid = UUID.randomUUID().toString();
    TokenEntity tknEntity = new TokenEntity();

    tknEntity.setEmailId(email);
    tknEntity.setExpiryTime(DateUtils.asDate(expiryTime));
    tknEntity.setStatus(ResetPasswordStatus.ACTIVE);
    tknEntity.setToken(uuid);

    tkeRepo.save(tknEntity);

    String fromString = UUID.nameUUIDFromBytes("SomeString".getBytes()).toString();
    System.out.println("For email " + mail + " UUID=" + uuid + " is stored at time " + new Date());
    System.out.println("UUID generated from String is " + fromString);
}
}

我将运行配置设置为 -e dhanrajtijare@gmail.com ..按预期方式获取电子邮件值。 我的问题在这行 tkeRepo.save(tknEntity); tkeRepo为空

1 个答案:

答案 0 :(得分:3)

这里

 TempTry main = new TempTry();

如果要创建实例yoursefl,@Autowire会如何工作?

到那时,您当前的实例似乎在应用程序上下文中,所以

@Override
public void run(String... args) throws Exception {
    logger.info("ApplicationStartupRunner run method Started !!");

    JCommander.newBuilder().addObject(this).build().parse(args);
    runtask();
}

我抛开了一个事实,恕我直言,将JCommander与Spring CLI混合使用是不好的-可以使用一个或另一个。