文章目录
1 Spring概述一种Java应用开发框架,而SpringMVC是针对Web的框架。
在Spring框架的lib文件夹中,分别有四个基础包,分别对应上图中Spring核心容器(Core Container)中的四个模块。
依赖翻转指:这里我们不使用new创建一个实例对象,而是依赖于Spring配置文件声明一个对象。
package top.lixiang007.ioc;
public interface UserDao {
public void say();
}
package top.lixiang007.ioc;
public class UserDaoImpl implements UserDao {
public void say() {
System.out.println("userDao say hello World to LiXiang!");
}
}
<?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-4.3.xsd">
<!-- 将指定类配置给Spring,让Spring创建其对象的实例 -->
<bean id="userDao" class="top.lixiang007.ioc.UserDaoImpl" />
<bean id="userService" class="top.lixiang007.ioc.UserServiceImpl" >
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
package top.lixiang007.ioc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
@Test
public void test(){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2.通过容器获取userDao实例
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
//3.调用实例中的say()方法
userDao.say();
}
}
4 DI代码实现
依赖注入的概念这里给出最通俗的理解:依赖注入让bean与bean之间以配置文件组织在一起,而不是以硬编码的方式耦合在一起。
这里我们采用set方法而不采用构造函数方法实现DI。
package top.lixiang007.ioc;
public interface UserService {
public void say();
}
package top.lixiang007.ioc;
public class UserServiceImpl implements UserService {
// 声明UserDao属性
private UserDao userDao;
// 添加UserDao属性的setter方法,用于实现依赖注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
// 实现的接口中方法
public void say() {
//调用userDao中的say()方法,并执行输出语句
this.userDao.say();
System.out.println("userService say hello World ");
}
}
<?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-4.3.xsd">
<!-- 将指定类配置给Spring,让Spring创建其对象的实例 -->
<bean id="userDao" class="top.lixiang007.ioc.UserDaoImpl" />
<bean id="userService" class="top.lixiang007.ioc.UserServiceImpl" >
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
package top.lixiang007.ioc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
@Test
public void test(){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2.通过容器获取userDao实例
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
//3.调用实例中的say()方法
userDao.say();
}
}
5 代码目录