spring注入实验

该博客展示了Spring框架中如何通过@Autowired注解实现接口的依赖注入,并在初始化方法@PostConstruct中调用接口方法。同时,通过ApplicationContext获取不同类型的Bean并进行操作,包括按类型和按名称获取Bean,以及获取所有Bean的Map。内容涵盖了Spring的组件扫描、依赖注入和Bean管理。
public interface TestInterface<T> {
    void test();
}
@Scope("prototype")
@Component("top")
public class TestSub1 implements TestInterface<TestSub1>{
    @Override
    public void test() {
        System.out.println("test1");
    }
}
@Component
public class TestSub2 implements TestInterface<TestSub2>{
    @Override
    public void test() {
        System.out.println("test2");
    }
}

@Component
public class Test {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 以下两种注入皆可
     */
    @Autowired
    private TestInterface<TestSub1> testInterface;

//    private TestInterface<TestSub1> testInterface;
//
//    public Test(TestInterface<TestSub1> testInterface) {
//        this.testInterface = testInterface;
//    }

    @PostConstruct
    public void init() {
        testInterface.test();
        for (int i = 0; i < 2; i++) {
            TestInterface bean = applicationContext.getBean(TestSub1.class);
            System.out.println(bean);
        }
        for (int i = 0; i < 2; i++) {
            TestInterface bean = applicationContext.getBean(TestSub2.class);
            System.out.println(bean);
        }

        for (int i = 0; i < 2; i++) {
            TestInterface bean = applicationContext.getBean("top", TestInterface.class);
            System.out.println(bean);
        }
        Map<String, TestInterface> map = applicationContext.getBeansOfType(TestInterface.class);
        for (String key : map.keySet()) {
            System.out.println(key);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值