Run the void installation method in Spring Context @ Configuration

I want to execute several customization methods in my Spring context.

I currently have the following code, but it does not work, as I say that they beansdo not have a return type either.

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

    ...

}

How to run this method automatically in context @Configurationwithout annotation @Bean?

+4
source share
2 answers

You can use annotation @PostConstructinstead @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");
    }

    ...

}
+4
source

Use @PostConstruct instead of @ bean

@PostConstruct

- Weld Reference :

  • bean ( @Inject), bean.
  • bean.
  • bean ( , ).
  • , @PostConstruct, .

, @PostConstruct ; beans, ..

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 -. , ,

:

+1

Source: https://habr.com/ru/post/1651298/


All Articles