Null pointer when auto-wiring in Spring Boot

AnonymousAlias :

Looking for what the standard is for auto-wiring an external sdk class I am trying this way but getting a null pointer.. I am using AmazonDynamoDBClient in a spring boot project. So I think I have my config class that is like this


@Configuration
public class DynamoDBClientBuilder {

    public AmazonDynamoDB amazonDynamoDBClient;
    @Bean
    public void DynamoDBClientBuilderInitializer() {

        amazonDynamoDBClient = this.initiateClient();

    }

    private AmazonDynamoDB initiateClient() {
        return AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(
                new AwsClientBuilder.EndpointConfiguration("http://localhost:4569", "us-west-1"))
                    .build();
    }
}

Then I have the class where I want to use that client in the spring project, is it best to do something like this outside of any methods

    @Autowired
    private DynamoDBClientBuilder db;
    private AmazonDynamoDB amazonDynamoDBClient = null;

And then this in either the constructor or where we want to use the client

amazonDynamoDBClient = db.amazonDynamoDBClient;

I'm not really sure why i am getting a null pointer it seems the config class isn't getting initiated before the class that wants to use it. Also would be interest to hear what the best practice is or is there a nicer way to do this.

Thanks

Paul_K :

Try this:

@Configuration
public class DynamoDBClientBuilder {
    @Bean
    public AmazonDynamoDB amazonDynamoDB() {
        return AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(
                new AwsClientBuilder.EndpointConfiguration("http://localhost:4569", "us-west-1"))
                .build();
    }
}

And then inject your bean like this:

@Autowired
AmazonDynamoDB amazonDynamoDB;

or with constructor (recommended):

private final AmazonDynamoDB amazonDynamoDB;

@Autowired
public MyClass(AmazonDynamoDB amazonDynamoDB) {
        this.amazonDynamoDB = amazonDynamoDB;
    }

And notice that your config calss must be covered with component scan to be able to create bean in spring context

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477767&siteId=1