一、对象属性类型的注入:
以MVC三层架构为例(Service、Controller、Dao),通常service和controller层需要对dao层的数据进行访问操作,这里以将dao层数据注入到Service层作为例子来说明
1、创建一个dao层的接口类
package com.xawl.spring.dao;
public interface UserDao {
void method1();
}
2、实现该接口的方法
package com.xawl.spring.dao;
public class UserDaoImp implements UserDao {
@Override
public void method1() {
System.out.println("this is UserDao");
}
}
3、创建Service层下的调用类
package com.xawl.spring.service;
import com.xawl.spring.dao.UserDao;
public class UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void userservice() {
System.out.println("this is userservice");
this.userDao.method1();
}
@Override
public String toString() {
return "UserService{" +
"userDao=" + userDao +
'}';
}
}
4、配置spring.xml(ref表示到跳转id)
5、创建测试类
package springdi;
import com.xawl.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestService {
public static void main(String[] args) {
//获取资源文件
String resources = "spring.xml";
//根据资源文件创建对象
ApplicationContext context = new ClassPathXmlApplicationContext(resources);
UserService userService = (UserService)context.getBean("userService");
System.out.println(userService);
userService.getUserDao();
userService.userservice();
}
}
6、输出结果
UserService{userDao=com.xawl.spring.dao.UserDaoImp@2f686d1f}
this is userservice
this is UserDao
二、复杂类型属性注入
数组、set、map、list四种类型的属性注入
1、创建bean实类
package com.xawl.spring.di;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Demo3 {
private String[] arrs;
private List list;
private Map map;
private Set set;
public String[] getArrs() {
return arrs;
}
public void setArrs(String[] arrs) {
this.arrs = arrs;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public Set getSet() {
return set;
}
public void setSet(Set set) {
this.set = set;
}
@Override
public String toString() {
return "Demo3{" +
"arrs=" + Arrays.toString(arrs) +
", list=" + list +
", map=" + map +
", set=" + set +
'}';
}
}
2、配置spring.xml
1
2
3
11
22
33
111
222
333
3、创建测试类
package springdi;
import com.xawl.spring.di.Demo3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDemo3 {
public static void main(String[] args) {
//获取数据源
String resources = "spring.xml";
//创建对象
ApplicationContext context = new ClassPathXmlApplicationContext(resources);
Demo3 demo3 = (Demo3) context.getBean("demo3");
System.out.println(demo3);
}
}
4、输出结果
Demo3{arrs=[1, 2, 3], list=[11, 22, 33], map={1=01, 2=02, 3=03}, set=[111, 222, 333]}
三、IOC和DI的关系和区别
IOC是容器,把对象交给spring处理
DI依赖注入,通过spring向类的属性设置值
依赖注入(DI)不能单独存在,需要在控制反转(IOC)的基础之上完成操作