1. 程式人生 > >Hello World(Spring)

Hello World(Spring)

自己 png world tro mls utf-8 狀態 pac 基於

今天真的是過得苦不堪言;一大早沒趕上班車,然後來大姨媽了,整天都處於將死的狀態;痛的吐了一下午;完全無法工作,一直在看著時間,快點到六點,然後六點好像還下不了班,得到六點半;為什麽女性要有痛經?????? 抓狂*100000

上午看了一下《Spring實戰》,看到了裝配bean,看完自動裝配後,感覺還是不懂;這本書已經無數次打開看不懂不看了,過段時間又打開還是一樣,反反復復循環了無數次了!!!還是找到了以前看的W3school上的Spring教程,先跟著這個看看,好理解一點,從最開始的地方講;一個月以前看過一點,但是那個時候急著想做項目,想馬上就要成大牛,就隨意的看了看;還是不行,沒有原理的支撐,靜不下心來學得話,走不遠。

先來個Spring的Hello World,這個一般都是所有學習的第一個程序吧;這是學習的鏈接 https://www.w3cschool.cn/wkspring/dgte1ica.html ;這個Hello World的項目似懂非懂的感覺;看是看懂了,但總感覺還是沒掌握的那種感覺。寫博客呢就是想鼓勵自己每天都學一點,記錄一下學習的狀態,情緒。

技術分享圖片

HelloSpring類: 定義了一個message變量,message變量的getter和setter方法,就是一個實體類

package com.lee.happy;

public class HelloSpring {
    
    
private String message; public void getMessage() { System.out.println("Your Message: " + message); } public void setMessage(String message) { this.message = message; } }

MainApp類:裏面是main方法,這裏面首先創建應用的上下文,加載配置文件;然後獲取名為Hello的bean

package com.lee.happy;

import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { //API ClassPathXmlApplicationContext() 創建應用的上下文;這個API加載beans的配置文件並最終基於所提供的API,它處理創建並初始化所有對象。及在配置文件中提到的beans ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); //使用已創建的上下文的getBean()方法來獲得所需的bean。這個方法使用bean的ID返回一個最終可以轉換為實際對象的通用對象,一旦有了對象就可以使用這個對象調用任何類的方法 HelloSpring obj = (HelloSpring) context.getBean("Hello"); obj.getMessage(); } }

Beans.xml:

<?xml version="1.0" encoding="UTF-8"?>

<!-- 粘合bean的粘合劑 -->

<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-3.0.xsd">
    
    <bean id="Hello" class="com.lee.happy.HelloSpring">
        <property name="message" value="Hello World"></property>        
    </bean>
</beans>

得到的結果:

技術分享圖片

碼雲:https://gitee.com/lemon_le/w3-Spring

Hello World(Spring)