Skip to content
Robin Drew edited this page Mar 4, 2025 · 16 revisions

Spring is a very large topic, so we will only be covering the essentials and hand-picked topics.

SpringBootApplication

@SpringBootApplication - A class annotated as an application should be defined as an entry point. The annotation includes:

  • @EnableAutoConfiguration - Enable the automatic configuration feature, a core part of Spring Boot.
  • @ComponentScan - Automatically scan this package and sub packages for components.
  • @Configuration - This class is a configuration and will automatically load any beans defined.

As with any entry point, a main method needs to be defined - in this case calling the SpringApplication run method.

@SpringBootApplication
public class WebServerApp {

   public static void main(String[] args) {
      SpringApplication.run(WebServerApp.class, args);
   }
}

Components

@Component - A class annotated as a component is automatically instantiated and registered as a bean if it is imported using @ComponentScan. Note that any parameters to the constructor selected will be injected by spring as if they were autowired, so need to be defined in a configuration.

There are a few special types of component:

  • @Controller - Marks the class as part of the presentation layer.
  • @Repository - Marks the class as part of the persistence layer.
  • @Service - Marks the class as part of the service layer.

Controller

@Controller - A class annotated as a controller is enabled for Spring MVC.

Configurations

@Configuration - A class annotated as a configuration is used to define configuration for an aspect of the application. Configurations can be imported by the spring application and by each other using the @Import annotation.

The entire configuration can also be made optional, even if imported, using one of the conditional annotations, for example:

  • @ConditionalOnProperty - if a property is set to a specific value
  • @ConditionalOnExpression - if a spring expression evaluates to true
  • @ConditionalOnResource - if a resource exists
  • @ConditionalOnBean / @ConditionalOnMissingBean - if a bean has or has not been defined
  • @ConditionalOnClass / @ConditionalOnMissingClass - if a class is or is not on the classpath

Beans

@Bean - A method annotated as a bean will have its return value automatically registered as a spring bean. Note that any parameters to the method will be injected by spring as if they were autowired, so need to be defined in a configuration.

Clone this wiki locally