粗浅理解依赖注入
1 先明确一个知识点,没有初始化的对象能用吗?
class A{
public A(){}
public void test(){
System.out.println("能输出吗?");
}
}
public class DIdemo {
public static void main(String[] args) {
//没有初始化的对象
A me;
me.test();
}
}
明显是不能用的,IDEA报错
Wrong:
Variable ‘me’ might not have been initialized
接下来我们分析一个依赖注入的最简单的模板
HelloDao类
public class HelloDao {
public void insert(){
System.out.println("Hello,This is insert");
}
}
HelloDemo类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("../../../applicationContext.xml",HelloDemo.class);
HelloService helloService= (HelloService) context.getBean("helloService");
helloService.sayHello();
}
}
HelloService类
public class HelloService {
private String name;
private HelloDao helloDao;
//这里是构造器注入
public HelloService(String name) {
this.name = name;
}
//这里是设置值注入(也可以理解为setter方法注入)
public void setHelloDao(HelloDao helloDao) {
this.helloDao = helloDao;
}
public HelloDao getHelloDao() {
return helloDao;
}
public void sayHello() {
System.out.println("hello" + this.name);
helloDao.insert();
}
}
分析:
这里的JavaBean,是HelloDao这个类。HelloService依赖于HelloDao。在HelloService当中,name属性和helloDao都被private封死了,无法对其进行初始化,那怎么办呢?
举个例子啊,你是个刺客,你有个任务:毒死暴戾的皇帝,现在给你个西瓜(对应封装好的类),和一针筒毒药,要求你将这个西瓜变毒(对应给这个西瓜的属性/对象初始化),还不破坏它,那就要进行注射了
private将HelloService类的属性封死了,封死了自然而然就不能通过外界赋值初始化了嘛。我们就要利用Spring的IoC容器这个针筒对HelloService类的属性赋值初始化
以上分析帮助你理解,现在看点直观的
以下是创建“针筒”的XML文件,是Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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="helloDao" class="com.example.demo3.HelloDao"/>
<!-- 用户服务 -->
<bean id="helloService" class="com.example.demo3.HelloService">
<!--Spring的两大注入方法之一:构造器注入-->
<constructor-arg name="name" value="Spring IoC Container"/>
<!--Spring的两大注入方法之二:设置值注入-->
<property name="helloDao" ref="helloDao"/>
</bean>
</beans>