I'm trying to run Hazelcast client application with Spring Boot without XML/YAML file but I can't find a way to manage my Hazelcast instance via Spring. This is my code
@Configuration
public class ConfigurationClass {
@Autowired
private Environment env;
@Bean
public ClientConfig clientConfig() {
ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig();
networkConfig.addAddress("127.0.0.1:5701").setSmartRouting(true).addOutboundPortDefinition("34700-34710").setRedoOperation(true).setConnectionTimeout(5000);
return clientConfig;
}
@Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
}
And when I try to Autowire Hazelcast instance into main class I get NULL
. Main class code
public class HazelcastServer implements Serializable {
private static final long serialVersionUID = -1798311083790835361L;
@Autowired
private static HazelcastInstance hazelcastInstance;
public static void main(String[] args) {
System.out.println("hazelcastInstance: " + hazelcastInstance);
}
}
You need to use a CommandLineRunner
so that Spring builds your context (in other words, creates your @Bean
s and autowires them)
See the tutorial here for a good start:
https://spring.io/guides/gs/spring-boot/
Basically, instead of the public static void main
you need to do something like this:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
The @SpringBootApplication
and SpringApplication.run
part tells Spring to do it's magic, read the tutorial I linked for the details.