这是实现spring InitializingBean的正确方法吗?

时间:2018-01-24 12:04:18

标签: java spring

我想在IdGenerator类中为主机和端口字段赋值,这是实现此目的的最佳方法吗?

注意:IdGenerator最好不要由spring管理, 客户端类可以将genId()称为静态方法。

@Component
public  class IdGenerator implements InitializingBean{

    private static final Logger LOGGER = LoggerFactory.getLogger(IdGenerator.class);

    @Value("${vesta.host}")
    private String host;

    @Value("${vesta.port}")
    private Integer port;

    static VestaHttpClient client;

    @Override
    public void afterPropertiesSet() {
        Assert.hasText(host);
        Assert.notNull(port);

        LOGGER.info("about to initial IdGenerator.");
        try {
            client = new VestaHttpClient(host, port);
        }catch(Exception e){
            LOGGER.info("IdGenerator  initialize failed .");
            throw new RuntimeException("----------VestaHttpClient initialize failed--------");
        }
        LOGGER.info("IdGenerator was successfully initialized.");
    }

    public static String genId(){
        return client.genId()+"";
    }

}

2 个答案:

答案 0 :(得分:0)

您可以简单地在VestaHttpClient类中将@Configuration构建为bean,使用PropertyPlaceholderConfigurer获取属性值并将其注入使用@Value注释的字段中。这是我嘲笑描述我的建议的一些代码(可能需要一些调整):

@Configuration
@PropertySource("classpath:example.properties")
public class MyConfiguration {


    @Value("${vesta.host}")
    private String host;

    @Value("${vesta.port}")
    private Integer port;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public VestaHttpClient get httpClient(){

        VestaHttpClient httpClient = null;

        try {
            client = new VestaHttpClient(host, port);
        }catch(Exception e){
        /*Omitted*/
        }
        return httpClient;
    }
}

答案 1 :(得分:0)

如果您想使用字段注入 所谓的“干净”配置bean 注入属性值,那么InitializingBean是验证属性的正确方法。

然而另一种方法是只使用构造函数注入并摆脱InitializingBean

@Component
public class IdGenerator {

    private static final Logger LOGGER = LoggerFactory.getLogger(IdGenerator.class);

    private String host;

    private Integer port;

    static VestaHttpClient client;

    @Autowired
    public WebProperties(@Value("${vesta.host}") String protocol,
                         @Value("${vesta.port}") Integer port) {
        // Validate properties and initialize VestaHttpClient
    }
}
相关问题