入门案例
进入官网下载jar包或者maven导包
新建工程
导入依赖包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.3.14</version> </dependency> <!-- 日志包 --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
创建普通类,在这个类创建普通方法
public class User{ public void add(){ System.out.println("添加..."); } }
创建Spring配置文件,在配置文件配置创建对象
配置文件为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 id="user" class="com.ye.User"> </bean> </beans>
进行测试代码编写
package com.ye; import javafx.application.Application; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author 夜灬瞬 * @date 2022/01/16 17:42 */ public class UserTest { @Test public void add() { //加载spring配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); //获取配置创建的对象 User user = context.getBean("user", User.class); System.out.println(user); user.add(); } }
com.ye.User@569cfc36
添加...