我希望在我的 Spring 上下文中执行几个设置方法。
我目前有以下代码,但它不起作用,因为我说它们是 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");
}
...
}
如何在没有 @Bean
注释的情况下通过 @Configuration
上下文自动运行此方法?
最佳答案
您可以使用@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");
}
...
}
关于java - 在 Spring Context @Configuration 中运行一个无效的设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38957851/