Spring作為一款成熟的Java框架,其優點和意義不用我多說,可以參考:https://m.w3cschool.cn/wkspring/pesy1icl.html
今天開始寫一下Spring家族的總結。
首先,按照慣例,先來一個hello world:
1.新建一個項目
我這里采用是maven的方式創建了父項目,然后在其下創建不同的module,好處是便于管理。不過你可以只創建一個普通的Java項目。
2.導入jar包或者引入maven依賴
你需要導入core,beans,context,expression4個spring的jar包或者相應的依賴,然后還有一個commons-logging的jar包或者依賴。
3.新建一個JavaBean
package com.spring.demo.bean;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class HelloWorld {
private String name;
}
4.編寫對應的spring配置文件bean.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">
<bean id="hello" class="com.spring.demo.bean.HelloWorld">
<property name="name" value="張三"/>
</bean>
</beans>
5.編寫測試類
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean-helloworld.xml");
HelloWorld hello = (HelloWorld) context.getBean("hello");
System.out.println(hello);
}
ok, 測試運行一下吧。