I. Introduction
"Spring annotation-driven development" series is a Spring-based version 4.3.11.RELEASE, develop presentations by way of comment.
Second, the project to build
1. The reference dependencies
Create a maven project, the introduction of related libraries. We rely on the principle of a minimum reference only spring-context and junit package.
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.11.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
2. Fill the container Spring
/ ** * @Configuration tell the Spring container This is a configuration file * / @Configuration public class MainConfig { / ** * @Bean inject a Bean, the default name for the method name, type of return value * You can also name through the @Bean Bean injection property specifies the name * / @Bean (name = "Person" ) public the Person Person () { return new new the Person ( "Joe Smith", 13 ); } }
Spring container above code is a simple method of assembly injection.
- @Configuration used to tell the Spring container This is a configuration file
- @Bean inject a Bean. By default, the name of the method name, type of return value. Bean can also specify the name of the injection by the name attribute of @Bean
3.Junit test
Read by AnnotationConfigApplicationContext annotation configuration and component configuration register into Spring container, and then get the object from the container and used.
public class MainConfigTest { @Test public void Test () { // embodiment annotated by refreshing the container, the container needs to specify and register configuration class the ApplicationContext applicationContext = new new AnnotationConfigApplicationContext (MainConfig. class ); // get the object from the container Person person = to applicationContext.getBean (the Person. class ); Assert.assertNotNull (Person); Assert.assertEquals (person.getName (), "Joe Smith" ); Assert.assertEquals (person.getAge (), 13 is ); } }
Third, the link
"Spring annotation-driven development (a) - Project to build"
"Spring annotation-driven development (b) - Component injection"