Spring实例解析之Annotation

本文基于Spring in action详细介绍了Spring的注解配置,包括自动装配的byName、byType、constructor、autodetect策略,以及@Autowired和@Resource的使用。通过实例演示了如何使用@Repository、@Service、@Component等注解定义Bean,以及通过注解读取properties文件。文章还探讨了初始化和销毁方法的不同实现方式。
摘要由CSDN通过智能技术生成

@(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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值