创建一个名为spring01的Maven Web 项目
并在main包中创建java和resources文件
创建好后在pom.xml中引入依赖
<!-- spring-webmvc 可以导入spring全部核心jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
创建dao层和service层
在dao层接口中写入say()方法并在实现类中实现方法
在service层接口中写入say()方法并在实现类中实现方法
在resources中创建applicationContext.xml并在 在applicationContext.xml中注册dao层的bean
创建测试类测试IOC
package com.lijunbo;
import com.lijunbo.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
public static void main(String[] args){
ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao =context.getBean("userDao",UserDao.class);
}
}
DI注入
在applicationContext.xml中加入service层的bean并关联dao层bean
<bean id="userService" class="com.lijunbo.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
创建DI测试类测试DI注入
package com.lijunbo;
import com.lijunbo.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDI {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.say();
}
}
测试成功