当前位置:首页 > IT技术 > 编程语言 > 正文

Spring 初学 - 1. 在基础java项目中运行Spring
2022-08-29 23:53:39

1. 下载并导入必须的包

需要以下jar包

1.1 从spring官网下载spring包

https://repo.spring.io/ui/native/release/org/springframework/spring/

下载spring-5.2.6.RELEASE-dist.zip,并解压获取需要的包

1.2 下载commons-logging-1.2-bin.zip

http://commons.apache.org/proper/commons-logging/download_logging.cgi

下载commons-logging-1.2-bin.zip并解压出需要的包

1.3 将包复制到idea中构建的java的基础项目中

File -> Project Structure

 

 

 

2. 创建简单的类实例并通过Spring进行实例化

2.1 创建user类文件(user.java)

package com.firstSpringTest.me;

public class user {
    public void say(){  
        System.out.println("I am a com.firstSpringTest.me.user class");
    }   
}

 

2.2 构建xml文件(ApplicationContext.xml)

创建方式:

 

 添加<bean>

<?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="user" class="com.firstSpringTest.me.user"></bean>
</beans>

2.3 创建测试类(SpringTest.java)

package com.firstSpringTest.me;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class springTest<sout> {
    public static void main(String[] args){
        ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        user user = (user) classPathXmlApplicationContext.getBean("user", user.class);
        user.say();
    }
}

 

运行结果如下

 

本文摘自 :https://www.cnblogs.com/

开通会员,享受整站包年服务立即开通 >