【Java Web】Spring入門
阿新 • • 發佈:2018-12-23
什麼是Spring
Spring是一個開源的框架,它的誕生是為了簡化企業級系統開發。
- 目的:解決企業級開發的複雜性
- 使用JavaBean替換EJB,並且提供更多的企業級應用
所以簡單的來說,Spring是一個輕量級的控制反轉(IOC)和麵向切面(AOP)的容器框架。
新建工程
如圖,勾選Spring和Web Application。點選Next繼續。
為專案取名字。完成後點選Finish。
新建Spring Config檔案
Spring檔案程式碼:
<?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">
</beans>
新建Bean類Student
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge () {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Setter注入
接著,在Spring檔案中設定一個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="obj" class="Student">
<property name="age" value="20"/>
<property name="name" value="狗二蛋"/>
</bean>
</beans>
這裡用class屬性設定Student類,id屬性設定一個唯一的標識,用 標籤為其屬性賦值。
獲取Bean
接著就可以在java中讀取Spring中xml程式碼,通過反射就可以獲得其中描述的bean物件了。程式碼如下:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml");
Student stu = applicationContext.getBean("obj",Student.class);
System.out.println(stu);
輸出:
Student{name=‘狗二蛋’, age=20}