一、springtoolSuite4下載下傳
1.概述
Spring Tools 4 是适用于您最喜歡的編碼環境的下一代 Spring 工具。它主要從頭開始重建,為開發基于 Spring 的企業應用程式提供世界一流的支援,無論您喜歡 Eclipse、Visual Studio Code 還是 Theia IDE。
換句話說, Spring Tool Suite是一個定制版的eclipse, 由spring framework官方在javaee版本的eclipse上包裝spring插件出來的版本, 其核心還是javaee版本的eclipse。
2.下載下傳
spring官網project中 spring tools4下載下傳,選擇相應的版本下載下傳;如果下載下傳下載下傳下來的是jar包,運作一下該jar包即可安裝;
二、建立java工程
1.在項目根目錄下建立lib檔案夾并且添加5個jar包;
5個jar包分别是:
- spring-beans
- spring-context
- spring-core
- spring-expression
- commons-logging
三、spring的使用
說明:spring方式,第一步:建立springioc容器;二、從IOC容器中擷取bean執行個體;三、調用方法;
1、建立類HelloWorld
1 package com.lixm.spring.beans;
2
3 public class HelloWorld {
4
5 private String name;
6
7 public String getName() {
8 return name;
9 }
10
11 public void setName(String name) {
12 this.name = name;
13 }
14
15 public void hello() {
16 System.out.println("hello "+name);
17 }
18
19 public HelloWorld() {
20 System.out.println("helloworld's constructor");
21 }
22
23
2.使用spring調用方法
步驟一、在src中建立spring的配置檔案(spring bean configuration file)applicationContext.xml(命名空間為 beans)
此時如果找不到spring的配置檔案(spring bean configuration file)則需要安裝其他軟體(選擇Add-on for spring tools 4)即可;
步驟一、xml配置beans
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
5
6 <!-- id 用來辨別class -->
7 <bean id="helloWorld2" class="com.lixm.spring.beans.HelloWorld">
8 <property name="name" value="Spring"></property> <!-- name 為屬性名 此處屬性名為name value為屬性的值 此處設定屬性name的值為Spring-->
9 </bean>
10 </beans>
步驟三、main的實作方式:
1 package com.lixm.spring.beans;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.ConfigurableApplicationContext;
5 import org.springframework.context.support.ClassPathXmlApplicationContext;
6
7 public class Main {
8 public static void main(String[] args) {
9 // 采用spring 方式
10
11 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
12 HelloWorld helloWorld2 = (HelloWorld) applicationContext.getBean("helloWorld2");
13 helloWorld2.hello();
14 ((ConfigurableApplicationContext) applicationContext).close();
15 }
16
17
運作main方法 控制台列印結果是:
helloworld's constructor
hello lixiuming
四、普通調用方式(不使用spring):
1 package com.lixm.spring.beans;
2
3 public class Main {
4 public static void main(String[] args) {
5 // 普通方式
6 // 建立 hellowWorld
7 HelloWorld helloWorld = new HelloWorld();
8 // 設定屬性
9 helloWorld.setName("lixiuming");
10 helloWorld.hello();
11
12 }
13
14