spring-config.xml中的第三方库的Bean

时间:2018-05-03 00:08:50

标签: java spring

我的课程如下所示

@Component
public class BillDAO {

    private DynamoDBMapper dynamoDBMapper;

    public void create(BillDO billDO) {
        AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.AP_SOUTH_1);
        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(builder.build());
        dynamoDBMapper.save(billDO);
    }
}

基本上,每次调用方法create时,我都不想构造dynamoDBMapper和builder实例。而是将这些注入豆类。可以做些什么?

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.tarkshala" />
</beans>

我确实找到了几个使用构造函数arg用于bean和factory-methods的示例。不知道如何在这里使用它。

1 个答案:

答案 0 :(得分:2)

您应该可以使用 @Configuration 注释来执行此操作。以下是 @Configuration 实现的代码示例,用于创建 AmazonDynamoDBClientBuilder&amp; DynamoDBMapper 为Spring 豆。

package com.tarkshala;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigurationAnnotationExample {

    @Bean
    public AmazonDynamoDBClientBuilder getAmazonDynamoDBClientBuilder() {
        return AmazonDynamoDBClientBuilder.standard().withRegion(Regions.AP_SOUTH_1);
    }

    @Bean
    public DynamoDBMapper getDynamoDBMapper(final AmazonDynamoDBClientBuilder builder) {
        return new DynamoDBMapper(builder.build());
    }
}

这是您修改后的BillDAO,以便使用注入的DynamoDBMapper。

package com.tarkshala;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillDAO {

    private DynamoDBMapper dynamoDBMapper;

    @Autowired
    public BillDAO(final DynamoDBMapper dynamoDBMapper) {
        this.dynamoDBMapper = dynamoDBMapper;
    }

    public void create(BillDO billDO) {
        dynamoDBMapper.save(billDO);
    }
}

由于您已在应用程序上下文xml中添加了 <context:component-scan base-package="com.tarkshala"/> ,因此从ConfigurationAnnotationExample类创建bean不再需要其他内容。