SpringBoot 配置类 @Bean 例子

本文通过一个Service调用Dao的例子,详细讲解了在SpringBoot中如何使用配置类和@Bean注解来实现组件的实例化和依赖注入,帮助理解SpringBoot的自动化配置原理。
摘要由CSDN通过智能技术生成

在Spring中 我们可以通过依赖注入 完成类之间的通信, SpringBoot则可以通过配置类 来实现我们所需要的功能。

我们以Service 调用 Dao 来做例子

//配置类
@Configuration
public class AppConfig {
   @Bean //通过@bean来实现<bean>的功能
   public StudentService studentService() {   //等价<bean id="">
	   StudentService stuService= new StudentService();
	   StudentDao studentDao= new StudentDao();
	   stuService.setStudentDao(studentDao);
	    return stuService;        //返回值 等价<bean class="">
   }
   @Bean StudentDao studentDao() {
	   StudentDao stuDao= new StudentDao();
	   return stuDao;
   }
   
}

Service


@Component
public class StudentService {

private static StudentDao studentdao;

public StudentService() {
	
}

public StudentDao getStudentDao() {
	return studentdao;
}

public void setStudentDao(StudentDao dao) {
	this.studentdao = dao;
}


@Test
	public void add() {
	 System.out.prin
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值