1.pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!-- 单元测试Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<finalName>cyb_spring</finalName>
<plugins>
<!-- 配置Maven的JDK编译级别 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
2.applicationContext.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="video" class="net.cybclass.sp.domain.Video">
<property name="id" value="9"></property>
<property name="title" value="Spring5.X课程"></property>
</bean>
<bean id="UserService" class="net.cybclass.sp.service.UserServiceImpl"></bean>
</beans>
3.UserService.java
package net.cybclass.sp.service;
/**
* @author: wangxiaobo
* @create: 2020-10-03 15:44
**/
public interface UserService {
void speak();
}
4.UserServiceImpl.java
package net.cybclass.sp.service;
/**
* @author: wangxiaobo
* @create: 2020-10-03 15:44
**/
public class UserServiceImpl implements UserService {
@Override
public void speak() {
System.out.println("王晓波博客:qq_34709784");
}
5.TestUserService.java
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author: wangxiaobo
* @create: 2020-10-03 15:49
**/
public class TestUserService {
@Test
public void TestIoc() {
ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml");
// 方式一
UserService service1 = context.getBean(UserService.class);
service1.speak();
// 方式二
UserService service2 = (UserService)context.getBean("UserService");
service2.speak();
}
}
运行