Which of the following syntax is correct to declare a bean of type class employee

Spring Boot @SpringBootApplication Annotation

Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It’s same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.

Spring Boot SpringApplication Class

Spring Boot SpringApplication class is used to bootstrap and launch a Spring application from a Java main method. This class automatically creates the ApplicationContext from the classpath, scan the configuration classes and launch the application. This class is very helpful in launching Spring MVC or Spring REST application using Spring Boot.

SpringBootApplication and SpringApplication Example

In the last tutorial on Spring RestController, we created a Spring RESTful web service and deployed it on Tomcat. We had to create web.xml and spring context file. We also had to manually add Spring MVC dependencies and manage their versions. Here we will change the project to run as a Spring Boot Application and get rid of configuration files. This will help in the quick testing of our application logic because we won’t have to manually build and deploy the project to the external Tomcat server.

You should check out the existing project from our GitHub Repository, in following sections we will make necessary changes to the project files.

Below image shows our final project structure.

Adding Spring Boot Maven Dependencies

The first step is to clean up pom.xml file and configure it for Spring Boot. Since it’s a REST web service, we only need spring-boot-starter-web dependency. However, we will have to keep JAXB dependencies because we are running on Java 10 and we want to support XML request and responses too. We will also have to add spring-boot-maven-plugin plugin, this plugin lets us run our simple java application as spring boot application. Here is our updated pom.xml file.

<project xmlns="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Spring-RestController</groupId> <artifactId>Spring-RestController</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>10</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- JAXB for XML Response needed to explicitly define from Java 9 onwards --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>javax.activation-api</artifactId> <version>1.2.0</version> </dependency> </dependencies> <build> <!-- added to remove Version from WAR file --> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

We can delete WebContent directory or leave it as is, it won’t be used by our Spring Boot application.

Spring Boot Application Class

Now we have to create a java class with main method, mark it with @SpringBootApplication annotation and invoke SpringApplication.run() method.

package com.journaldev.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } }

Just run the class as Java application and it will produce following output. I have removed some loggers that we don’t care about here. The application will not quit and wait for client requests.

2018-06-18 14:33:51.276 INFO 3830 --- [ main] c.j.spring.SpringBootRestApplication : Starting SpringBootRestApplication on pankaj with PID 3830 (/Users/pankaj/Documents/eclipse-jee-workspace/Spring-RestController/target/classes started by pankaj in /Users/pankaj/Documents/eclipse-jee-workspace/Spring-RestController) 2018-06-18 14:33:51.280 INFO 3830 --- [ main] c.j.spring.SpringBootRestApplication : No active profile set, falling back to default profiles: default 2018-06-18 14:33:51.332 INFO 3830 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@38467116: startup date [Mon Jun 18 14:33:51 IST 2018]; root of context hierarchy 2018-06-18 14:33:52.311 INFO 3830 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2018-06-18 14:33:52.344 INFO 3830 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-06-18 14:33:52.344 INFO 3830 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31 2018-06-18 14:33:52.453 INFO 3830 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-06-18 14:33:52.453 INFO 3830 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1127 ms 2018-06-18 14:33:52.564 INFO 3830 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2018-06-18 14:33:52.927 INFO 3830 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/get/{id}],methods=[GET]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.getEmployeeByID(int) 2018-06-18 14:33:52.928 INFO 3830 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/getAll],methods=[GET]}" onto public java.util.List<com.journaldev.spring.model.Employee> com.journaldev.spring.controller.EmployeeRestController.getAllEmployees() 2018-06-18 14:33:52.929 INFO 3830 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/create],methods=[POST]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.createEmployee(com.journaldev.spring.model.Employee) 2018-06-18 14:33:52.929 INFO 3830 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/search/{name}],methods=[GET]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.getEmployeeByName(java.lang.String) 2018-06-18 14:33:52.929 INFO 3830 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rest/employee/delete/{id}],methods=[DELETE]}" onto public com.journaldev.spring.model.Employee com.journaldev.spring.controller.EmployeeRestController.deleteEmployeeByID(int) 2018-06-18 14:33:53.079 INFO 3830 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-06-18 14:33:53.118 INFO 3830 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2018-06-18 14:33:53.124 INFO 3830 --- [ main] c.j.spring.SpringBootRestApplication : Started SpringBootRestApplication in 2.204 seconds (JVM running for 2.633)

Some important points we can deduce from logs:

  1. Spring Boot Application Process ID is 3830.
  2. Spring Boot Application is launching Tomcat on port 8080.
  3. Our application context path is “”. It means when invoking our APIs we don’t need to provide servlet context.
  4. The logger prints all the APIs that are configured, see messages Mapped "{[/rest/employee/get/{id}],methods=[GET]}" etc.

Below image shows an example invocation of the APIs exposed by our Spring Boot Application.

SpringBootApplication scanBasePackages

By default SpringApplication scans the configuration class package and all it’s sub-pacakges. So if our SpringBootRestApplication class is in com.journaldev.spring.main package, then it won’t scan com.journaldev.spring.controller package. We can fix this situation using SpringBootApplication scanBasePackages property.

@SpringBootApplication(scanBasePackages="com.journaldev.spring") public class SpringBootRestApplication { }

Spring Boot Auto-Configured Beans

Since Spring Boot provides auto-configuration, there are a lot of beans getting configured by it. We can get a list of these beans using below code snippet.

ApplicationContext ctx = SpringApplication.run(SpringBootRestApplication.class, args); String[] beans = ctx.getBeanDefinitionNames(); for(String s : beans) System.out.println(s);

Below is the list of beans configured by our spring boot application.

org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory springBootRestApplication org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory employeeRestController employeeRepository org.springframework.boot.autoconfigure.AutoConfigurationPackages org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration org.springframework.boot.autoconfigure.condition.BeanTypeRegistry propertySourcesPlaceholderConfigurer org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration websocketContainerCustomizer org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat tomcatServletWebServerFactory org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration servletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer server-org.springframework.boot.autoconfigure.web.ServerProperties org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata webServerFactoryCustomizerBeanPostProcessor errorPageRegistrarBeanPostProcessor org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration dispatcherServlet mainDispatcherServletPathProvider spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration dispatcherServletRegistration org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration defaultValidator methodValidationPostProcessor org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration error beanNameViewResolver org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration conventionErrorViewResolver org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration errorAttributes basicErrorController errorPageCustomizer preserveErrorControllerTargetClassPostProcessor spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration faviconHandlerMapping faviconRequestHandler org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration requestMappingHandlerAdapter requestMappingHandlerMapping mvcConversionService mvcValidator mvcContentNegotiationManager mvcPathMatcher mvcUrlPathHelper viewControllerHandlerMapping beanNameHandlerMapping resourceHandlerMapping mvcResourceUrlProvider defaultServletHandlerMapping mvcUriComponentsContributor httpRequestHandlerAdapter simpleControllerHandlerAdapter handlerExceptionResolver mvcViewResolver mvcHandlerMappingIntrospector org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter defaultViewResolver viewResolver welcomePageHandlerMapping requestContextFilter org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration hiddenHttpMethodFilter httpPutFormContentFilter org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration mbeanExporter objectNamingStrategy mbeanServer org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration standardJacksonObjectMapperBuilderCustomizer spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration jacksonObjectMapperBuilder org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration parameterNamesModule org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration jacksonObjectMapper org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration jsonComponentModule org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration stringHttpMessageConverter spring.http.encoding-org.springframework.boot.autoconfigure.http.HttpEncodingProperties org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration mappingJackson2HttpMessageConverter org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration messageConverters org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration jacksonCodecCustomizer org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration restTemplateBuilder org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration tomcatWebServerFactoryCustomizer org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration characterEncodingFilter localeCharsetMappingsCustomizer org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration multipartConfigElement multipartResolver spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties

That’s a huge list, there are many auto-configured beans that we are not using. We can optimize our spring boot application by disabling these using @SpringBootApplication exclude or excludeName property. Below code snippet will disable JMX and Multipart autoconfiguration.

@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = { org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration.class, org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration.class }) public class SpringBootRestApplication { }

Note that if we try to exclude any non-auto-configuration classes, we will get an error and our application won’t start.

@SpringBootApplication(scanBasePackages = "com.journaldev.spring", exclude = {com.journaldev.spring.controller.EmployeeRestController.class }) public class SpringBootRestApplication { }

Above code snippet will throw the following error:

2018-06-18 15:10:43.602 ERROR 3899 --- [main] o.s.boot.SpringApplication: Application run failed java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes: - com.journaldev.spring.controller.EmployeeRestController

That’s all for SpringBootApplication annotation and SpringApplication example.

You can download the final project from our GitHub Repository.

How do you declare a class as bean?

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .

How do you define a class as bean in spring boot?

While the @Component annotation is used to decorate classes that are auto-detected by Spring scanning, the @Bean annotation is used to explicitly declare a bean creation. The @Value annotation is used to set the value of the app.name property into the appName parameter. logger.info("Application name: {}", appName.

What is @bean annotation in spring boot?

One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework.

What is @bean annotation in Java?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .

Toplist

Neuester Beitrag

Stichworte