Spring Framework 6 教學 (三) Ioc 使用 XML 配置

  • Post category:Ioc / Spring 6

Spring Framework 6 跟以往 Spring 的版本一樣有 Ioc 的機制,如果你對物件的轉換(cast)有概念的話,這個部分對你來說就不困難。

轉換的物件,必須要有繼承或實作界面的關係,才能進行轉換(cast)。

使用XML進行配置

在專案的 src 中增加 application.xml。

設定 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"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  
  <bean id="myObj1" class="com.myspring.MyObj1" /> 

</beans>

建立物件的 package

新增 Java class

增加 method hi()

另外,再新增一個 Java 的 main 類別,進行測試。

底下紅字的部分,是尚未取得 Spring Jar 造成的。

在 pom.xml 中,增加新的設定

	    <dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>6.0.12</version>
		</dependency>

紅字消失了,但是,仍有紅字表示,還需要進行調整。

Maven 網站中,可以看到相依性,將下面的 Jar 設定一口氣增加吧!

<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-aop</artifactId>
		    <version>6.0.12</version>
		</dependency>
	    <dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-beans</artifactId>
		    <version>6.0.12</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-expression</artifactId>
		    <version>6.0.12</version>
		</dependency>

另外,將原本的 application.xml ,另外放到新的 resource 資料夾中。

Spring Framework 6 需要的 Jar 比較完整了

在 Use1.java 中,新增呼叫 hi() 的程式!

呼叫成功!

Spring Framework 6 第一支程式呼叫成功。

讀取 XML 的三種方式

  1. ClassPathXmlApplicationContext
  2. FileSystemXMLApplicationContext
  3. XmlWebApplicationContext

之前是使用 ClassPathXmlApplicationContext 。

底下分別列出 FileSystemXMLApplicationContext 與 XmlWebApplicationContext 的程式

String path = "C:/myProject/src/main/resources/applicationcontext/account-bean-config.xml";

ApplicationContext context = new FileSystemXmlApplicationContext(path);

public class MyXmlWebApplicationInitializer implements WebApplicationInitializer {

  public void onStartup(ServletContext container) throws ServletException {
    XmlWebApplicationContext context = new XmlWebApplicationContext();
    context.setConfigLocation("/WEB-INF/spring/applicationContext.xml");
    context.setServletContext(container);

    // Servlet configuration
  }
}