Spring項目創建

Spring的創建

1.先建立Maven項目的常規步驟

2.導入依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>

3.編寫實體類

package com.kuang.pojo;

public class Hello {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void show(){
        System.out.println(name+"---------");
    }
}

4.resources中創建beans.xml,這個就是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">

   <!--bean就是java對象 , 由Spring創建和管理-->
   <bean id="hello" class="com.kuang.pojo.Hello">
       <property name="name" value="Spring"/>
   </bean>

</beans>

5.測試類進行測試

@Test
public void test(){
   //解析beans.xml文件 , 生成管理相應的Bean對象
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //getBean : 參數即爲spring配置文件中bean的id .
   Hello hello = (Hello) context.getBean("hello");
   hello.show();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章