Starting with Spring 3.x, Spring provides the ability to configure Java. Java configuration is the configuration method recommended by Spring 4.x, which can completely replace xml configuration; Java configuration is also the configuration method recommended by Spring Boot.
Java configuration is achieved through @Configuration and @Bean .
1. @Configuration declares that the current class is a configuration class, which is equivalent to a Spring-configured xml file
. 2. The @Bean annotation is on the method, declaring that the return value of the current method is a Bean.
@Configuration public class JavaConfig { @Bean public TestService TestService(){ return new TestService(); } }
Annotation configuration
In the Spring 2.x era, with the annotation support brought by JDK 1.5, Spring provides annotations for declaring beans (such as @Service, @Component), which greatly reduces the amount of configuration. Compared with using XML, Spring uses annotations to describe the configuration of beans. Because class annotations are in the source code of a class, it can obtain the benefits of type safety checking and can support refactoring well.
@Service public class TestService { public TestService(){ System.out.println("TestService.TestService()"); } public void SayHello(){ System.out.println("Hello World!"); } }
Summary
When to use Java configuration or annotation configuration? The main principles are: use Java configuration (such as database-related configuration, MVC-related configuration) for global configuration, and use annotation configuration for business bean configuration.