Spring学习(二)——依赖注入

今天来学习Spring最基础的特性——依赖注入,依赖注入大体上分为三种方式:自动化装配Bean、通过Java代码装配Bean、通过XML文件装配Bean,当然,更多情况下用的最多的是“混合配置”!个人觉得虽然通过注解配置非常方便,但有时候通过XML配置却是极佳的选择,因此将“通过XML文件配置”和“混合配置”放在一起讲述。

一、自动化装配Bean

适用范围:

  • 自己写的类

注意:虽然自动化装配Bean这种方式能适用多种场景,但如果要将第三方库的组件装配到你的应用中,是没有办法在别人写好的类上添加@Component的注解的!

实现过程:

  • 组件扫描:Spring发现上下文中创建的bean
  • 自动装配:Spring自动满足bean之间的依赖

1. 创建Bean

创建接口:

package cool.gjh.beans;

/**
 * 车
 *
 * @author ACE_GJH
 */
public interface Car {

    /**
     * 驾驶
     */
    void drive();

}

创建Bean:

package cool.gjh.beans;

import org.springframework.stereotype.Component;

/**
 * 自行车
 *
 * @author ACE_GJH
 */
@Component
public class Bicycle implements Car{
    /**
     * 驾驶
     */
    @Override
    public void drive() {
        System.out.println("骑自行车开始兜风......");
    }
}

小结:@Component和@Service、@Controller等一样,告知了Spring哪些类会成为Bean。

2. 创建Spring配置类

package cool.gjh.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Spring配置类
 *
 * @author ACE_GJH
 */
@ComponentScan(basePackages = "cool.gjh")
@Configuration
public class Config {
}

小结:@Configuration让这个类成为一个配置类;@ComponentScan(basePackages = “cool.gjh”)告诉了Spring去扫描哪些包下的Bean,如果不加“basePackages”说明的话,默认是扫描这个配置类所在的包及其子包。

3. 创建测试类进行测试

package test.cool.gjh.spring;

import cool.gjh.beans.Car;
import cool.gjh.config.Config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class SpringDITest {

    @Autowired
    private Car car;

    /**
     * 测试依赖注入
     */
    @Test
    public void testInject(){
        car.drive();
    }

}

测试结果:
测试结果

二、通过Java代码装配Bean

这种情况就是适用注入"通过第三方库"获取到的对象,一起来看下吧。

1. 模拟创建第三方库

Animal接口:

package cool.gjh.zoo;

/**
 * 动物接口
 *
 * @author ACE_GJH
 */
public interface Animal {
    /**
     * 叫
     */
    void speak();
}

Cat实现类:

package cool.gjh.zoo;

/**
 * 猫
 * @author ACE_GJH
 */
public class Cat implements Animal {
    /**
     * 叫
     */
    @Override
    public void speak() {
        System.out.println("Miao Miao...");
    }
}

Dog实现类

package cool.gjh.zoo;

/**
 * 狗
 * @author ACE_GJH
 */
public class Dog implements Animal {
    /**
     * 叫
     */
    @Override
    public void speak() {
        System.out.println("Wang Wang...");
    }
}

ZooFactory动物园工厂:

package cool.gjh.zoo;

/**
 * 动物园工厂
 * <p>
 *     盛产动物
 * </p>
 * @author ACE_GJH
 */
public class ZooFactory {

    /**
     * 根据动物名获取动物实例
     *
     * @param name 动物名
     * @return 动物实例
     */
    public static Animal getAnimalByName(String name){
        switch (name){
            case "Cat":return new Cat();
            case "Dog":return new Dog();
            default:throw new RuntimeException("The animal does not exist.");
        }
    }

}

2. 在配置类中创建Bean

Config配置类中,通过方法返回对象来获取Bean,先看代码:

package cool.gjh.config;

import cool.gjh.zoo.Animal;
import cool.gjh.zoo.ZooFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Spring配置类
 *
 * @author ACE_GJH
 */
@ComponentScan(basePackages = "cool.gjh")
@Configuration
public class Config {
    @Bean(name = "singleDog")
    public Animal dog(){
        return ZooFactory.getAnimalByName("Dog");
    }
    @Bean
    public Animal cat(){
        return ZooFactory.getAnimalByName("Cat");
    }
}

这里有些注意的点:

  1. 方法都是public修饰
  2. 方法的返回类型根据自己的需要来写
  3. 方法名与注入的对象名必须一致,否则报错;也可以指定注入时的对象名,在方法上的注解@Bean上加入(name = “xxxx”)即可

3. 在测试类中进行测试

package test.cool.gjh.spring;

import cool.gjh.config.Config;
import cool.gjh.zoo.Animal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class SpringDITest {


    @Autowired
    private Animal singleDog;
    @Autowired
    private Animal cat;

    /**
     * 测试通过Java代码装配Bean
     */
    @Test
    public void testJavaDITest(){

        singleDog.speak();
        cat.speak();

    }
}

测试结果:
测试结果

三、通过XML文件装配Bean(混合配置)

这种方式装配Bean以Spring整合Mybatis为例最具代表性,限于篇幅,我把我的这篇博客链接写在下面:

Spring学习(四)——Spring整合Mybatis

至此,Spring基础的依赖注入方式就说完了,至于更高级的装配方式,我们下回再说。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭建華

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值