Where should I put @Bean in Spring Boot?
This article describes solution of problem, where to put @Bean
function using Spring Boot. The preferred way of keeping beans is class annotated with @Configuration
. Below source codes show simple bean location examples.
1. Bean location tempalte
In this section default approach for creating beans is presented. It is recommended to look on next point that contains practical example.
ServerConfig
class is annoted with @Configuration
, beanName()
function is annoted with @Bean
, The best location for ServerConfig
class is package that contains class with main()
function, that runs all application - SpringApplication.run(....class, args)
call.
Note:
ServerConfig
class name can be replaced with any other class name.
package my.projest.package;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServerConfig {
@Bean
public ConfigurationClass beanName() {
ConfigurationClass configuration = new ConfigurationClass();
// setting configuration...
return configuration;
}
}
2. Web server factory bean example
In this section web server factory bean location is presented. This configuration is used by Spring Boot 2 to change default port, but the bean can be changed with any configuration with @Bean
annotation.
ServerConfig.java
file:
package com.dirask.examples;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServerConfig {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(connector -> {
connector.setPort(80);
});
return factory;
}
}
ServerConfig.java
file location: