Languages
[Edit]
EN

Where should I put @Bean in Spring Boot?

13 points
Created by:
Tomeriko
413

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:

Server port with ServerConfig.java file location - Spring Boot 2.x.x + IntelliJ
Server port with ServerConfig.java file location - Spring Boot 2.x.x + IntelliJ

Alternative titles

  1. Spring Boot - bean configuration location
  2. Spring Boot - location of bean configuration
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join