发表于: 2025-03-28 21:02:09
0 5
今天完成的事情:
今天学习了设值注入
设值注入(Setter Injection)概念
设值注入是一种依赖注入(Dependency Injection, DI)的方式,通过调用类的setter方法将依赖对象注入到目标对象中。它是Spring框架中最常用的依赖注入方式之一。
核心思想
依赖注入:将一个对象所需要的依赖(例如服务、组件等)从外部提供给它,而不是由对象自己创建。
设值注入:依赖通过setter方法传递给目标对象。
与构造器注入(Constructor Injection)相比,设值注入更加灵活,因为它允许在对象创建之后动态地设置依赖关系。
示例:
定义依赖类
// 依赖类:ServiceA
public class ServiceA {
public void doSomething() {
System.out.println("ServiceA is doing something.");
}
}
// 依赖类:ServiceB
public class ServiceB {
public void performTask() {
System.out.println("ServiceB is performing a task.");
}
}
定义目标类
// 目标类:MyController
public class MyController {
// 声明依赖项
private ServiceA serviceA;
private ServiceB serviceB;
// 设值注入:为依赖项提供setter方法
public void setServiceA(ServiceA serviceA) {
this.serviceA = serviceA;
}
public void setServiceB(ServiceB serviceB) {
this.serviceB = serviceB;
}
// 使用依赖项
public void execute() {
serviceA.doSomething();
serviceB.performTask();
}
}
Spring配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 定义依赖Bean -->
<bean id="serviceA" class="com.example.ServiceA" />
<bean id="serviceB" class="com.example.ServiceB" />
<!-- 定义目标Bean,并通过setter注入依赖 -->
<bean id="myController" class="com.example.MyController">
<property name="serviceA" ref="serviceA" />
<property name="serviceB" ref="serviceB" />
</bean>
</beans>
测试代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// 加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取目标Bean
MyController myController = (MyController) context.getBean("myController");
// 执行方法
myController.execute();
}
}
明天计划的事情:(一定要写非常细致的内容)
继续学习spring
遇到的问题:(遇到什么困难,怎么解决的)
无
收获:(通过今天的学习,学到了什么知识)
学会了使用set注入
评论