當(dāng)前位置:首頁 > IT技術(shù) > 編程語言 > 正文

Spring 初學(xué) - 1. 在基礎(chǔ)java項(xiàng)目中運(yùn)行Spring
2022-08-29 23:53:39

1. 下載并導(dǎo)入必須的包

需要以下jar包

1.1 從spring官網(wǎng)下載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 將包復(fù)制到idea中構(gòu)建的java的基礎(chǔ)項(xiàng)目中

File -> Project Structure

?

?

?

2. 創(chuàng)建簡單的類實(shí)例并通過Spring進(jìn)行實(shí)例化

2.1 創(chuàng)建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 構(gòu)建xml文件(ApplicationContext.xml)

創(chuàng)建方式:

?

?添加<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 創(chuàng)建測試類(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();
    }
}

?

運(yùn)行結(jié)果如下

?

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

開通會(huì)員,享受整站包年服務(wù)立即開通 >