在Spring Context @Configuration中运行void设置方法 [英] Run a void setup method in Spring Context @Configuration

查看:100
本文介绍了在Spring Context @Configuration中运行void设置方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在Spring Context中执行几种设置方法.

I wish to perform a couple of setup methods within my Spring Context.

我目前有以下代码,但由于我说它们是beans并且没有返回类型而无法正常工作.

I currently have the following code but it doesn't work as I am saying they are beans and have no return type.

@Configuration
@Component
public class MyServerContext {

    ...

    // Works
    @Bean
    public UserData userData() {
        UserData userData = new AWSUserDataFetcher(urlUtil()).fetchUserData();
        return userData;
    }   

    // Doesn't work
    @Bean
    public void setupKeyTrustStores() {
        // Setup TrustStore & KeyStore
        System.setProperty(SYS_TRUST_STORE, userData().get(TRUST_STORE_PATH));
        System.setProperty(SYS_TRUST_STORE_PASSWORD, userData().get(TRUST_STORE_PASSWORD));
        System.setProperty(SYS_KEY_STORE, userData().get(KEY_STORE_PATH));
        System.setProperty(SYS_KEY_STORE_PASSWORD, userData().get(KEY_STORE_PASSWORD));

        // Prevents handshake alert: unrecognized_name
        System.setProperty(ENABLE_SNI_EXTENSION, "false");
    }

    ...

}

如何在没有@Bean批注的情况下通过@Configuration上下文自动运行此方法?

How can I run this method automatically by the @Configuration context without the @Bean annotation?

推荐答案

您可以使用@PostConstruct注释代替@Bean:

@Configuration
@Component
public class MyServerContext {

    @Autowired
    private UserData userData; // autowire the result of userData() bean method

    @Bean
    public UserData userData() {
        UserData userData = new AWSUserDataFetcher(urlUtil()).fetchUserData();
        return userData;
    }   

    @PostConstruct
    public void setupKeyTrustStores() {
        // Setup TrustStore & KeyStore
        System.setProperty(SYS_TRUST_STORE, userData.get(TRUST_STORE_PATH));
        System.setProperty(SYS_TRUST_STORE_PASSWORD, userData.get(TRUST_STORE_PASSWORD));
        System.setProperty(SYS_KEY_STORE, userData.get(KEY_STORE_PATH));
        System.setProperty(SYS_KEY_STORE_PASSWORD, userData.get(KEY_STORE_PASSWORD));

        // Prevents handshake alert: unrecognized_name
        System.setProperty(ENABLE_SNI_EXTENSION, "false");
    }

    ...

}

这篇关于在Spring Context @Configuration中运行void设置方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆