合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
案例代码:https://gitee.com/flymini/codes01/tree/master/spring_/com-learn-spring01 **** **1. 创建一个 maven 项目** ```xml <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.19.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.19.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.2.19.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <dependency> <scope>compile</scope> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> </dependencies> ``` **2. 创建一个实体类** ```java @Data public class User { private String userName; } ``` **3. 将实体类注入到 IoC 容器中** *`resources/ApplicationContentext.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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置User的bean --> <bean id="user" class="com.learn.spring01.pojo.User"> <property name="userName" value="张三"/> </bean> </beans> ``` **4. 调用 IoC 容器中的 bean 组件** ```java public class UserTest { /** 获取 IoC 容器 */ private final ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContentext.xml"); @Test public void getUserName() { //调用 IoC 容器中的 User User user = context.getBean(User.class); //张三 System.out.println(user.getUserName()); } } ```