1. 程式人生 > 實用技巧 >Spring——HelloSpring第一個專案

Spring——HelloSpring第一個專案

首先建立實體類

package com.yl.pojo;

public class Hello {
private String str;

public String getStr() {
return str;
}

public void setStr(String str) {
this.str = str;
}

@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}

在recourses目錄下建立一個spring配置檔案:beans.xml

<?xml version="1.0" encoding="GBK"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--使用Spring來建立物件,在Spring中這些都成為Bean
型別 變數名 = new 型別();
Hello hello = new Hello();
bean = 物件 new Hello();
id = 變數名
class = new的物件
property 給物件中的屬性賦值
-->
<bean id="hello" class="com.yl.pojo.Hello">
<property name="str" value="Spring"/>
</bean>

</beans>

測試:

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());
}

到目前為止,已經徹底不用在程式中改動了,要實現不同的操作,只需要在xml配置檔案中進行修改,物件由Spring來建立 管理和裝配

對應改造上一個程式:

  • 增加配置檔案

    <?xml version="1.0" encoding="GBK"?>
    <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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="mysqlImpl" class="com.yl.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.yl.dao.UserDaoOracleImpl"/>
    <bean id="userServiceImpl" class="com.yl.service.UserServiceImpl">
    <!--
    ref:引用Spring容器中建立好的物件
    value:具體的值,基本資料型別和String
    -->
    <property name="userDao" ref="oracleImpl"/>
    </bean>

    </beans>
  • 測試:

    public static void main(String[] args) {
    //獲取ApplicationContext,拿到Spring的容器
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    //需要什麼就直接get什麼
    UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
    userServiceImpl.getUser();
    }

控制

誰來控制物件的建立,傳統應用程式的物件是由程式本身控制建立的,使用Spring後,物件是由Spring來建立的

反轉

程式本身不建立物件,而被動的接收物件

依賴注入

就是利用set方法來進行注入的

IOC是一種程式設計思想,由主動的程式設計變為被動的接受