@(Spring)
*本文主要参考Spring in action(第三版),并以自己的实例进行了实现。
上一篇Spring实例解析之XML装配Bean简单介绍了Spring使用xml来装配Bean,这一篇将会继续使用同样的实例来简单介绍Spring的annotation来简化xml的配置。
1.maven依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
</dependencies>
2.Spring-autowiring(自动装配)
Spring有多种方式来处理Bean的依赖关系。这里会给出四种自动装配策略:byName,byType,constructor,autodetect。
2.1接口介绍
本文将围绕People接口,来渐渐展开。
public interface People {
void doWorking();
}
2.2声明简单Bean
Himma(搬砖工)实现People接口。并有两个参数,birckNum(砖头数),pitNum(填坑数)。
package com.spring;
public class Himma implements People {
//默认一天搬100块砖
private Integer brickNum = 100;
//默认填5个坑
private Integer pitNum = 5;
public Himma(){
}
public Himma(int brickNum){
this.brickNum = brickNum;
}
public Himma(int brickNum, int pitNum){
this.brickNum = brickNum;