1、pom.xml引入spring
<dependencies> <!-- 引入spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.1.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies>
2、写一个业务层接口和它的实现类
public interface UserService { public void save(); } public class UserServiceImpl implements UserService { @Override public void save() { System.out.println("runing..."); } }
3、在resources中编写spring配置文件applicationContext.xml,在xml中配置控制的资源,也就是刚刚编写的实现类
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置spring控制的资源 --> <bean id="userService" class="com.hw.service.impl.UserServiceImpl"/> </beans>
4、测试:加载配置文件、获取资源
public class UserServiceTest { @Test public void shouldAnswerWithTrue() { //加载springcontext的配置文件 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取资源 UserService userService = (UserService) ctx.getBean("userService"); userService.save(); } }
标签:xml,入门,配置文件,spring,案例,userService,UserService,ioc,public From: https://www.cnblogs.com/weiduaini/p/17288152.html