依赖:如果B类中有个A类对象,则说B类依赖A类
注入的三种方式:
<1>构造函数注入:
目标类:
package com.spring.DI;
import java.util.Date;
public class BookeServiceImp implements BookService {
private String diver;
Integer port ;
BookDao dao;
public BookeServiceImp(String diver, Integer port, BookDao dao) {
this.diver = diver;
this.port = port;
this.dao = dao;
}
public void addBook() {
System.out.println(diver+port+dao);
}
}
依赖类:
package com.spring.DI;
public class BookeDaoImp implements BookDao {
public void addBook() {
System.out.println("Id aad book");
}
}
文件配置:
<!-- 构造器注入
diver port是基本数据注入
today是其他bean注入
-->
<bean id="bookService" class="com.spring.DI.BookeServiceImp">
<constructor-arg name="diver" value="com.mysql.jdbc"></constructor-arg>
<constructor-arg name="port" value="3306"></constructor-arg>
<constructor-arg name="dao" ref="bookeDao"></constructor-arg>
</bean>
<bean id="bookeDao" class="com.spring.DI.BookeDaoImp"></bean>
<2>set方法注入:
和构造器注入基本没多打区别,只是使用的是默认构造函数,配置标签使用的
目标类:
package com.spring.DI;
import java.util.Date;
public class BookeServiceImp2 implements BookService {
private String diver;
Integer port ;
BookDao dao;
public void setDiver(String diver) {
this.diver = diver;
}
public void setPort(Integer port) {
this.port = port;
}
public void setDao(BookDao dao) {
this.dao = dao;
}
public void addBook() {
System.out.println(diver+port+dao);
}
}
配置文件:
<bean id="bookDao" class="com.spring.DI.BookeDaoImp"></bean>
<!--setter方法注入
-->
<bean id="bookService" class="com.spring.DI.BookeServiceImp2">
<property name="diver" value="mysql.com.jdbc"></property>
<property name="port" value="3306"></property>
<property name= "dao" ref="bookDao"></property>
</bean>
<3>注解注入:
注入的三种数据类型:
<1>基本类型:
<2>其他bean类型(必须在spring中配置过的bean)
<3>复合类型(集合)
目标类:
package com.spring.DI;
import java.util.ArrayList;
import java.util.Map;
public class ComphensiveDI {
private ArrayList<String> myArra;
private Map<String,Integer> myMap;
public void setMyArra(ArrayList<String> myArra) {
this.myArra = myArra;
}
public void setMyMap(Map<String, Integer> myMap) {
this.myMap = myMap;
}
public void print() {
System.out.println(myArra);
System.out.println(myMap);
}
}
文件配置:
<!-- 复合类的配置 -->
<bean id="complex" class="com.spring.DI.ComphensiveDI">
<property name = "myArra">
<list>
<value>AAAA</value>
</list>
</property>
<property name="myMap">
<map>
<entry key="name" value="5555555"></entry>
</map>
</property>
</bean>