Javaconfig of spring framework, springjavaconfig
Introduction:With the release of java 5 and the emergence of Guice, a dependency injection framework based on pure java annotation, spring has released and continuously improved the dependency binding description method based on java code and annotation metadata, that is, the javaconfig Project
The dependency binding Description Based on javaconfig basically maps to the earliest XML-based configuration method.
I. expression form layer
The xml-based configuration method is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Beans xmlns = "http://www.springframework.org/schema/beans"
Xmlns: context = "http://www.springframework.org/schema/context"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation ="
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context.xsd
Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd>
<! -Bean definition->
</Beans>
The configuration method based on javaconfig is as follows:
@ Configuration
Public class MockConfiguration {
// Bean Definition
}
Any one is labeled@ ConfigurationJava class definition is a configuration class of javaconfig.
Ii. 1. Register bean DefinitionThe xml-based configuration method is as follows:
<Bean id = "mockService" class = "... MockServiceImpl">
...
</Bean>The configuration method based on javaconfig is as follows:
@ Configuration
Public class MockConfiguration {
@ Bean
Public MockService mockService (){
Return new MockServiceImpl ():
}
}
The return value of any method labeled @ Bean is registered to the IoC container of Spring as a bean definition. The method name will be the id defined by the bean by default.
2. Batch define bean RegistrationThe xml-based configuration method is as follows:
<Context: component-scanBase-package = "..."/>
In combination with @ Component and @ Repository, bean definition classes labeled with annotation are collected to spring IoC containers in batches.The configuration method based on javaconfig is as follows:
@ ComponentScan (String [] basePackages)
Note: @ ComponentScan is a key component of the springboot framework.
Iv. Dependency InjectionThe xml-based configuration method is as follows:
<Bean id = "mockService" class = "... MockServiceImpl">
<Property name = "dependencyService" ref ="DependencyService">
</Bean>
<Bean id ="DependencyService"Class = "...DependencyServiceImpl "/>
The configuration method based on javaconfig is as follows:
@ Configuration
Public class MockConfiguration {
@ Bean
Public MockService mockService (){
Return new MockServiceImpl (DependencyService ()):
}
@ Bean
Public DEpendencyServiceDependencyService(){
Return newDependencyServiceImpl ():
}
}
If a bean depends on other beans, you can directly call the creation method of bean dependencies in the corresponding javaconfig class.