【Spring】依赖注入三种方式

本文详细介绍了Spring框架中的三种依赖注入方式:构造器注入、set和get方法注入以及使用Filed注入(使用注解)。具体包括如何在beans.xml文件中配置依赖注入,以及在基于注解的方式下实现依赖注入的步骤。

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

1.通过构造器

2.通过set和get方法

3.使用Filed注入(annocation) 


构造器:

public interface PersonService {

public void save();

}

public class PersonServiceBean implements PersonService {

private PersonDao personDao;
private String name;

public PersonServiceBean(PersonDao personDao, String name) {
super();
this.personDao = personDao;
this.name = name;
}

public void save() {
System.out.println(name);
personDao.add();
}
}


public interface PersonDao {

public void add();

}

public interface PersonDao {

public void add();

}

beans.xml

<bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
<constructor-arg index="0" type="cn.itcast.dao.PersonDao" ref="personDao"></constructor-arg>
<constructor-arg index="1" value="高明"></constructor-arg>
</bean>

set和get构造

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />

	<bean id="personDao" class="com.gaodml.spring.persondaoimpl.PersonDaoBean"></bean>
	<bean id="personService" class="com.gaodml.spring.personserviceimpl.PersonServiceBean">

	</bean>
</beans> 

package com.gaodml.spring.personserviceimpl;
import javax.annotation.Resource;

import com.gaodml.spring.persondao.PersonDao;
import com.gaodml.spring.personservice.PersonService;


public class PersonServiceBean implements PersonService {
	
	@Resource
	private PersonDao personDao;
	
	@Override
	public void save(){
		System.out.println("save()方法调用");
		personDao.add();
	}

	public PersonServiceBean() {
		
	}

}

注解注入:

public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

<bean id="personDao" class="com.gaodml.spring.persondaoimpl.PersonDaoBean"></bean>
	<bean id="personService" class="com.gaodml.spring.personserviceimpl.PersonServiceBean">
		<constructor-arg index="0" ref="personDao"></constructor-arg>
	</bean> 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值