初識Spring(入門篇)
阿新 • • 發佈:2021-03-29
一、Spring入門—建立hellospringhello
1.編寫一個hello實體類
public class Hello{
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show (){
System.out.println("hello="+name);
}
}
2.編寫spring檔案,這裡命名為benas.xml(檔案在resource目錄下建立)
bean就是java物件,由spring建立和管理
id=變數名
class=new的物件;
property 相當於給物件中的屬性設定一個值!
<bean id="hello" class="com.lele.ioctestdemo.pojo.Hello" >
<property name="name" value="Spring"/>
</bean>
3.接下來就可以進行測試了.
public class MyTest {
public static void main(String[] args) {
//獲取spring上下文物件
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//我們的物件都在spring中管理了,要使用的話直接去裡面取出來就可以了
Hello hello= (Hello) context.getBean("hello");
System.out.println(hello.toString());
輸出結果:
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" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
小結:
bean id 變數名與context.getBean(“hello”);名必須一致
所有的類都需要裝配到bean裡面,所有的bean都需要通過容器去取,容器裡的bean拿出來就是一個物件。