(1)pom.xml
pom.xml文件是在整個項目下面,該xml的主要作用是:導入框架的jar包及其所依賴的jar包,導入的jar包是寫在<dependencies></dependencies>中
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>oracle.MavenPro</groupId> <artifactId>MyFirstPro</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.1.RELEASE</version> </dependency> </dependencies> </project>
(2)spring.xml
spring.xml是通過spring框架來創建對象,而不需要在類中創建對象。
下面通過一個簡單的sayhello例子來說明:
定義一個接口 ISayHello
package com.service; public interface ISayHello { public void sayHello(); }
定義 接口ISayHello 的實現類 SayHelloImple
package com.service.imple; import com.service.ISayHello; public class SayHelloImple implements ISayHello{ @Override public void sayHello() { System.out.println("hello!!!"); } }
通過spring.xml來實例化對象,其中class屬性是實現類的全路徑,id是實例化對象的別名(hello)。
<?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-3.0.xsd"> <bean id="hello" class="com.service.imple.SayHelloImple"></bean> </beans>
其中下面這段代碼是告訴spring,通過什么編碼來解析<bean>
新建一個test類
package com.service; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.imple.SayHelloImple; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); SayHelloImple sayhello = (SayHelloImple) context.getBean("hello"); sayhello.sayHello(); } }
下面這段代碼是加載 spring.xml 文件
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
下面代碼是獲取實例化的對象hello
SayHelloImple sayhello =
(SayHelloImple) context.getBean("hello");
運行結果為: