@Autowired Bean返回空值

时间:2019-04-04 21:31:34

标签: spring javabeans

我在春季启动应用程序中使用jar使用第三方库,并创建了我需要使用的类的单例bean。但是,当我自动连接此bean时,它总是返回null

从库中创建类的单例并自动连接Bean

@Configuration
public class IdGenConfig {   
    private static final Instant baseTime = ZonedDateTime.of(2019, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC")).toInstant();

    @Bean//this too 3rd party lib class
    public MachineId concreteMachineId(){
        return new ConcreteMachineId();
    }

    @Bean(name = "camflakeIdGen")//this is 3rd party library
    public Camflake camflake(final MachineId machineId){
        return new Camflake(machineId, baseTime);
    }}

@Service
@Log4j2
public class IdGenerator implements IdentifierGenerator {
    @Autowired
    @Qualifier("camflakeIdGen")
    Camflake camflake;//here null

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        try {
            log.debug("generate(): action=generate; state=start; message=\"generating id\";");
            Long id = camflake.next();
            log.debug("generate(): action=generate; state=finish; message=\"generating id\";id={};",id);
            return id;
        } catch (Exception ex) {
            log.fatal("generate(): action=generate; state=error; message=\"generating id\"; error=\"{}\";", ex.getMessage(), ex);
            throw new Exception(ErrorType.SYSTEM_ERROR);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

····
 @Bean(name = "camflakeIdGen")//this is 3rd party library
    public Camflake camflake(final MachineId machineId){
        return new Camflake(machineId, baseTime);
    }}

我认为这是你的错!

@Configuration
public class IdGenConfig {   
    private static final Instant baseTime = ZonedDateTime.of(2019, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC")).toInstant();

    @Bean//this too 3rd party lib class
    public MachineId concreteMachineId(){
        return new ConcreteMachineId();
    }

    @Bean(name = "camflakeIdGen")// try this way!!
    public Camflake camflake(){
        return new Camflake(concreteMachineId(), baseTime);
    }}