在Spring Context @Configuration中运行void setup方法

时间:2016-08-15 15:12:18

标签: java spring spring-mvc spring-boot annotations

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

我目前有以下代码,但它不起作用,因为我说它们是beans并且没有返回类型。

@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");
    }

    ...

}

如何在没有@Configuration注释的@Bean上下文中自动运行此方法?

2 个答案:

答案 0 :(得分:11)

您可以使用@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");
    }

    ...

}

答案 1 :(得分:1)

Use @PostConstruct instead of @bean

@PostConstruct

由于Weld Reference注入和初始化按此顺序发生;

  1. 首先,容器调用bean构造函数(默认值) 构造函数或带注释的@Inject),以获取实例 豆子。
  2. 接下来,容器初始化所有注入的字段的值 豆子。
  3. 接下来,容器调用bean的所有初始化方法(调用 订单不便携,不要依赖它。)
  4. 最后,调用@PostConstruct方法(如果有的话)。
  5. 因此,使用@PostConstruct的目的很明确;它让你有机会初始化注入的bean,资源等。

    public class Person {
    
        // you may have injected beans, resources etc.
    
        public Person() {
            System.out.println("Constructor is called...");
        }
    
        @PostConstruct
        public void init() {
            System.out.println("@PostConstruct is called...");
        } }
    

    因此,注入Person bean的输出将是;

      

    构造函数被调用...

         

    @PostConstruct被称为......

    关于@PostConstruct的一个重点是,如果您尝试通过生产者方法注入和初始化bean,则不会调用它。因为使用生成器方法意味着您使用新关键字以编程方式创建,初始化和注入bean。

    资源链接:

    1. CDI Dependency Injection @PostConstruct and @PreDestroy Example
    2. Why use @PostConstruct?