CGB2110-DAY03-Spring-DI

1. Spring的依赖注入

1.1 依赖注入案例

1.1.1 定义接口Pet

package com.jt.demo4;

public interface Pet {

    void hello();
}

1.1.2 定义Dog类

package com.jt.demo4;
import org.springframework.stereotype.Component;
//将该类交给Spring容器管理  key:abc,value:反射机制创建对象
@Component
public class Dog implements Pet{

    @Override
    public void hello() {
        System.out.println("快到圣诞节了!!!");
    }
}

1.1.3 定义User类

package com.jt.demo4;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component  //将User对象交给Spring容器管理
public class User {
    /**
     *  注入:将spring容器中的对象进行引用!!!
     *  @Autowired: 可以将容器中对象进行注入
     *      1.按照类型注入
     *          如果注入的类型是接口,则自动的查找其实现类对象进行注入
     *          注意事项: 一般spring框架内部的接口都是单实现,特殊条件下可以多实现
     *      2.按照名称注入
     */
    @Autowired
    private Pet pet;

    public void hello(){
        pet.hello();
    }
}

1.1.4 编辑配置类

package com.jt.demo4;

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

@Configuration
@ComponentScan("com.jt.demo4")
public class SpringConfig {

    
}

1.1.5 编辑测试代码

package com.jt.demo4;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringDI {
    public static void main(String[] args) {
        ApplicationContext context =
                new AnnotationConfigApplicationContext(SpringConfig.class);
        User user = context.getBean(User.class);
        user.hello();
    }
}

上一篇:《驱动学习 —— input子系统》


下一篇:关于编程的那些事-7