牛客网项目——前置技术(一):Spring Ioc

本文介绍了如何在Spring Boot项目中利用Spring IoC容器进行bean的初始化、销毁、第三方bean管理,以及@Autowired注解的简化应用。涵盖了配置类扫描、bean生命周期管理、外部bean配置和依赖注入的实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 基本介绍

在这里插入图片描述

	public static void main(String[] args) {
   
		SpringApplication.run(CommunityApplication.class, args);
	}

上述的方法除了开启TomCat,自动创建了Spring容器,会自动扫描某些包下某些bean。
会扫描配置类所在包和子包带有注解的内容,一共有四个注解()
在这里插入图片描述
在测试代码中启用配置类

@ContextConfiguration(classes = CommunityApplication.class)

2. 得到Spring Ioc容器

实现接口 ApplicationContextAware
重写方法 setApplicationContext
把容器暂存为 applicationContext
当程序启动之后,applicationContext 就会被传进来自动进行记录

@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
class CommunityApplicationTests implements ApplicationContextAware {
   

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
   
		this.applicationContext = applicationContext;
	}
}

在测试方法中使用容器

	@Test //从容器获取bean
	public void testApplicationContext() {
   
		System.out.println(applicationContext);

		//通过接口名(类名)得到bean,@Primary 优先级高先被获取
		AlphDao alphDao = applicationContext.getBean(AlphDao.class);
		System.out.println(alphDao.select());

		//通过名字得到bean,并转成AlphDAO类型
		AlphDao alphDao1 = applicationContext.getBean("alphaHibernate", AlphDao.class);
		System.out.println(alphDao1.select());
	}

在这里插入图片描述
java.dao 包中内容

package com.psynowcoder.community.community.dao;

public interface AlphDao {
   
    String select() ;
}
package com.psynowcoder.community.community.dao;

import org.springframework.stereotype.Repository;

@Repository("alphaHibernate") //给bean一个名字
public class AlphaDaoHibernateImpl implements AlphDao{
   
    @Override
    public String select() {
   
        return "Hibernate";
    }
}
package com.psynowcoder.community.community.dao;

import org.springframework.context.annotation.Primary;
import org.springframew
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

平什么阿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值